首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >在.Net中,为什么在调用Type.GetCustomAttributes(true)时不返回接口上声明的属性?

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

Stack Overflow用户
提问于 2010-11-11 01:03:04
回答 2查看 977关注 0票数 5

作为对this question的回答,我尝试在一个类上使用Type.GetCustomAttributes(true),该类实现了一个接口,接口上定义了一个属性。我惊讶地发现GetCustomAttributes没有返回接口上定义的属性。为什么不是呢?接口不是继承链的一部分吗?

示例代码:

代码语言:javascript
运行
复制
[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
{
}

输出:无

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2010-11-11 01:08:13

我不相信在已实现的接口上定义的属性可以合理地继承。考虑一下这种情况:

代码语言:javascript
运行
复制
[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 { }

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

票数 9
EN

Stack Overflow用户

发布于 2010-11-11 01:06:14

因为类型DoesntOverrideAttr没有任何自定义属性。它实现的接口(请记住,类不是从interface...it继承的,所以在继承链上获取属性仍然不会包括来自接口的属性):

代码语言:javascript
运行
复制
// 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());
}
票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/4146965

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档