在 .Net 中,为什么调用 Type.GetCustomAttributes(true) 时没有在返回的接口上声明属性?
在回答 这个问题时,我尝试使用 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
{
}
输出:无
In answer to this question I tried to use Type.GetCustomAttributes(true)
on a class which implements an interface which has an Attribute defined on it. I was surprised to discover that GetCustomAttributes
didn't return the attribute defined on the interface. Why doesn't it? Aren't interfaces part of the inheritance chain?
Sample code:
[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
{
}
Outputs: Nothing
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我不相信在实现的接口上定义的属性可以合理地继承。考虑这种情况:
由于该属性指定不允许出现多个,您希望如何处理这种情况?
I don't believe attributes defined on implemented interfaces can be reasonably inherited. Consider this case:
Since the attribute specifies that multiples are not allowed, how would you expect this situation to be handled?
因为类型
DoesntOverrideAttr
没有任何自定义属性。它实现的接口确实如此(请记住,类不是从接口继承的......它实现了它,因此在继承链上获取属性仍然不会包含来自接口的属性):Because the type
DoesntOverrideAttr
doesn't have any custom attributes. The Interface that it implements does (remember, a class doesn't inherit from an interface...it implements it so getting attributes up the inheritance chain still won't include attributes from interfaces):