110,536
社区成员
发帖
与我相关
我的任务
分享
[AttributeUsage(AttributeTargets.All, AllowMultiple = true, Inherited = true)]
public class MyAttribute : Attribute
{
public MyAttribute(int n)
{
System.Console.WriteLine("Hello MyAttribute");
}
public string _s { get; set; }
private int _n { get; set; }
}
使用MyAttribute修饰函数foo:
[My(123, _s = "456")]
public void foo()
{
System.Console.WriteLine("hello foo");
}
遍历MyAttribute修饰过的foo:
List<object> GetAttributeValue<TAttribute>(Type attType, bool collectInheritedAttributes, Func<TAttribute, object> valueSelector) where TAttribute : Attribute
{
List<object> objs = new List<object>();
var atts = attType.GetCustomAttributes(typeof(TAttribute), collectInheritedAttributes);
foreach(var att in atts)
{
if (att != null)//这里一次都没有触发
{
object o = valueSelector(att as TAttribute);
if (o != null)
objs.Add(o);
}
}
return objs;
}
ICollection<System.Reflection.Assembly> baseAssemblies = AppDomain.CurrentDomain.GetAssemblies();
foreach (var a in baseAssemblies)
{
GetAttributeValue<MyAttribute>(a.GetType(), true, at => at);
}
在GetAttributeValue中没有获得MyAttribute属性,我哪里写错了吗?
感谢关注。
[AttributeUsage(AttributeTargets.All, AllowMultiple = true, Inherited = true)]
public class MyAttribute : Attribute
{
public MyAttribute(int n)
{
System.Console.WriteLine("Hello MyAttribute");
}
public string _s { get; set; }
private int _n { get; set; }
}
public class MainClass{
[My(123, _s = "456")]
public void foo()
{
System.Console.WriteLine("hello foo");
}
static void Main(string[] args)
{
IList<MethodInfo> list = System.AppDomain.CurrentDomain.GetAssemblies()
.SelectMany(a => a.GetTypes())
.SelectMany(t => t.GetMethods())
.Where
(
p => p.GetCustomAttributes(typeof(MyAttribute), true).Any()
).ToList();
foreach (MethodInfo p in list )
{
Console.WriteLine(p.Name);
}
}
}
讓我知道這是否可以解決您的問題。