在.Net中,为什么在调用Type.GetCustomAttributes(true)时返回的接口上没有声明属性?

Wes*_*ser 5 .net inheritance attributes interface getcustomattributes

在回答这个问题时,我尝试Type.GetCustomAttributes(true)在一个实现接口的类上使用,该接口上定义了一个Attribute.我很惊讶地发现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
{
}
Run Code Online (Sandbox Code Playgroud)

输出:没什么

cdh*_*wie 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 { }
Run Code Online (Sandbox Code Playgroud)

由于该属性指定不允许多个,因此您希望如何处理这种情况?