如何从基类获取继承的属性

时间:2014-08-07 04:36:22

标签: c#

有没有办法在B类上获取GetMethods的结果,因此它将包含来自基类A的方法,而不会将属性添加到重写方法。

Class A
{
    [My]
    public virtual void test(){}
}
Class B , A
{
    public override void test(){}
}

IEnumerable<MethodInfo> typeMethodList = typeof(A).GetMethods().Where(x => x.GetCustomAttributes(typeof(MyAttribute), false).Any());
   ---Result {Test}

IEnumerable<MethodInfo> typeMethodList = typeof(B).GetMethods().Where(x => x.GetCustomAttributes(typeof(MyAttribute), false).Any());
   ---Result Empty list

2 个答案:

答案 0 :(得分:1)

尝试GetCustomAttributes(typeof(MyAttribute), true)

答案 1 :(得分:1)

使您的属性继承或明确指定您要搜索祖先的属性。

[System.AttributeUsage(Inherited = true)]
public class MyAttribute : Attribute { }

http://msdn.microsoft.com/en-us/library/system.attributeusageattribute.inherited.aspx

IEnumerable<MethodInfo> typeMethodList = typeof(B)
    .GetMethods()
    .Any(x => x.GetCustomAttributes(type: typeof(MyAttribute), inherit: false));

http://msdn.microsoft.com/en-us/library/ms130871(v=vs.110).aspx