在回答这个问题时,我尝试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
{
}
输出:无