C#属性继承没有像我预期的那样工作

C#属性继承没有像我预期的那样工作,c#,inheritance,properties,attributes,C#,Inheritance,Properties,Attributes,我在基类中有一个属性,上面有一些属性: [MyAttribute1] [MyAttribute2] public virtual int Count { get { // some logic here } set { // some logic here } } 在派生类中,我已经这样做了,因为我想将MyAttribute3添加到属性中,并且我无法编辑基类: [MyAttribute3] public override int Count { ge

我在基类中有一个属性,上面有一些属性:

[MyAttribute1]
[MyAttribute2]
public virtual int Count
{
  get
  {
    // some logic here
  }
  set
  {
    // some logic here
  }
}
在派生类中,我已经这样做了,因为我想将MyAttribute3添加到属性中,并且我无法编辑基类:

[MyAttribute3]
public override int Count
{
  get
  {
     return base.Count;
  }
  set
  {
     base.Count = value;
  }
}


但是,该属性现在的行为似乎没有MyAttribute1和MyAttribute2。是我做错了什么,还是属性没有继承?

默认情况下属性没有继承。您可以使用
AttributeUsage
属性指定此项:

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

如果您只是使用.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);

属性显示数组中的2个元素。

使用属性的代码是您自己的吗?那也请把它寄出去。简言之,在获取属性时,您可以选择是否包含继承树doh中更高层次的属性-我希望不是这样!不,这不是我自己的代码。我也许能说服他们改变它,虽然我猜…好吧,没有属性继承!您必须将MyAttribute1和MyAttribute2添加到override属性。当您说它“表现得好像上面没有MyAttribute1和MyAttribute2”时,上下文是什么?属性是如何被访问的,访问的目的是什么,属性应该做什么而不是做什么?