如果您只是使用方法 .GetType().GetCustomAttributes(true),这对我来说似乎工作正常,即使您设置 Inherited=true,它也不会真正返回任何属性。
[AttributeUsage(AttributeTargets.Property, Inherited = true, AllowMultiple = true)]
sealed class MyAttribute : Attribute
{
public MyAttribute()
{
}
}
[AttributeUsage(AttributeTargets.Property, Inherited = true, AllowMultiple = true)]
sealed class MyAttribute1 : Attribute
{
public MyAttribute1()
{
}
}
class Class1
{
[MyAttribute()]
public virtual string test { get; set; }
}
class Class2 : Class1
{
[MyAttribute1()]
public override string test
{
get { return base.test; }
set { base.test = value; }
}
}
然后从类 2 中获取自定义属性。
Class2 a = new Class2();
MemberInfo memberInfo = typeof(Class2).GetMember("test")[0];
object[] attributes = Attribute.GetCustomAttributes(memberInfo, true);
attributes 显示数组中的 2 个元素。