作为对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
{
}
输出:无
发布于 2010-11-11 01:08:13
我不相信在已实现的接口上定义的属性可以合理地继承。考虑一下这种情况:
[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-11 01:06:14
因为类型DoesntOverrideAttr
没有任何自定义属性。它实现的接口(请记住,类不是从interface...it继承的,所以在继承链上获取属性仍然不会包括来自接口的属性):
// 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());
}
https://stackoverflow.com/questions/4146965
复制相似问题