gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 07:07:47 27 4
gpt4 key购买 nike

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

示例代码:

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

输出:无

最佳答案

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

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

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

关于.net - 在 .Net 中,为什么调用 Type.GetCustomAttributes(true) 时不返回接口(interface)上声明的属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4146965/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com