代码之家  ›  专栏  ›  技术社区  ›  Wesley Wiser

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

  •  5
  • Wesley Wiser  · 技术社区  · 14 年前

    this question 我试着用 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
    {
    }
    

    输出:无

    2 回复  |  直到 7 年前
        1
  •  9
  •   cdhowie    14 年前

    我不相信在实现的接口上定义的属性可以合理地继承。考虑这个案例:

    [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 { }
    

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

        2
  •  4
  •   Justin Niessner    14 年前

    因为类型 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());
    }
    
    推荐文章