gpt4 book ai didi

c# - 属性继承与反射

转载 作者:太空狗 更新时间:2023-10-29 21:52:13 26 4
gpt4 key购买 nike

我已经创建了一个自定义属性来装饰一些我想在运行时查询的类:

[AttributeUsage(AttributeTargets.Class, AllowMultiple=false, Inherited=true)]
public class ExampleAttribute : Attribute
{
public ExampleAttribute(string name)
{
this.Name = name;
}

public string Name
{
get;
private set;
}
}

这些类中的每一个都派生自一个抽象基类:

[Example("BaseExample")]
public abstract class ExampleContentControl : UserControl
{
// class contents here
}

public class DerivedControl : ExampleContentControl
{
// class contents here
}

是否需要将此属性放在每个派生类上,即使我将它添加到基类中?该属性被标记为可继承,但是当我进行查询时,我只看到基类而没有看到派生类。

来自 another thread :

var typesWithMyAttribute = 
from a in AppDomain.CurrentDomain.GetAssemblies()
from t in a.GetTypes()
let attributes = t.GetCustomAttributes(typeof(ExampleAttribute), true)
where attributes != null && attributes.Length > 0
select new { Type = t, Attributes = attributes.Cast<ExampleAttribute>() };

谢谢,wTs

最佳答案

我按原样运行你的代码,得到以下结果:

{ Type = ConsoleApplication2.ExampleContentControl, Attributes = ConsoleApplication2.ExampleAttribute[] }
{ Type = ConsoleApplication2.DerivedControl, Attributes = ConsoleApplication2.ExampleAttribute[] }

所以它似乎有效......你确定没有其他事情发生吗?

关于c# - 属性继承与反射,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3301258/

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