5

在回答这个问题时,我尝试Type.GetCustomAttributes(true)在一个实现接口的类上使用该接口定义了一个属性。我惊讶地发现GetCustomAttributes没有返回接口上定义的属性。为什么不呢?接口不是继承链的一部分吗?

示例代码:

[Attr()]
public interface IInterface { }

public class DoesntOverrideAttr : IInterface { }

class Program
{
    static void Main(string[] args)
    {
        foreach (var attr in typeof(DoesntOverrideAttr).GetCustomAttributes(true))
            Console.WriteLine("DoesntOverrideAttr: " + attr.ToString());
    }
}

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

输出:无

4

2 回答 2

9

我不相信在实现的接口上定义的属性可以被合理地继承。考虑这种情况:

[AttributeUsage(Inherited=true, AllowMultiple=false)]
public class SomethingAttribute : Attribute {
    public string Value { get; set; }

    public SomethingAttribute(string value) {
        Value = value;
    }
}

[Something("hello")]
public interface A { }

[Something("world")]
public interface B { }

public class C : A, B { }

由于该属性指定不允许使用倍数,您希望如何处理这种情况?

于 2010-11-10T17:08:12.730 回答
4

因为该类型DoesntOverrideAttr没有任何自定义属性。它实现的接口确实(请记住,一个类不会从接口继承......它实现了它,因此在继承链上获取属性仍然不会包括来自接口的属性):

// This code doesn't check to see if the type implements the interface.
// It should.
foreach(var attr in typeof(DoesntOverrideAttr)
                        .GetInterface("IInterface")
                        .GetCustomAttributes(true))
{
    Console.WriteLine("IInterface: " + attr.ToString());
}
于 2010-11-10T17:06:13.770 回答