Won*_*ane 6 c# reflection inheritance attributes custom-attributes
我创建了一个自定义属性来装饰我想在运行时查询的许多类:
[AttributeUsage(AttributeTargets.Class, AllowMultiple=false, Inherited=true)]
public class ExampleAttribute : Attribute
{
public ExampleAttribute(string name)
{
this.Name = name;
}
public string Name
{
get;
private set;
}
}
Run Code Online (Sandbox Code Playgroud)
这些类中的每一个都派生自一个抽象基类:
[Example("BaseExample")]
public abstract class ExampleContentControl : UserControl
{
// class contents here
}
public class DerivedControl : ExampleContentControl
{
// class contents here
}
Run Code Online (Sandbox Code Playgroud)
我是否需要将此属性放在每个派生类上,即使我将其添加到基类中?该属性被标记为可继承,但是当我执行查询时,我只看到基类而不是派生类.
从另一个线程:
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>() };
Run Code Online (Sandbox Code Playgroud)
谢谢,wTs
我按原样运行你的代码,得到以下结果:
{ Type = ConsoleApplication2.ExampleContentControl, Attributes = ConsoleApplication2.ExampleAttribute[] }
{ Type = ConsoleApplication2.DerivedControl, Attributes = ConsoleApplication2.ExampleAttribute[] }
Run Code Online (Sandbox Code Playgroud)
所以它似乎有效...你确定没有发生其他事情吗?
归档时间: |
|
查看次数: |
487 次 |
最近记录: |