什么时候运行?它是针对我应用它的每个对象运行的,还是只运行一次?它可以做任何事情,或者它的行为受到限制吗?
我创建了一个自定义属性来装饰我想在运行时查询的许多类:
[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 …Run Code Online (Sandbox Code Playgroud) 我有史以来第一次真正需要手动进行装配扫描.我遇到了C# - 如何使用自定义类属性枚举所有类?这让我很开心
var typesWithMyAttribute =
(from assembly in AppDomain.CurrentDomain.GetAssemblies()
from type in assembly.GetTypes()
let attributes = type.GetCustomAttributes(typeof(SomeAttribute), true)
where attributes != null && attributes.Length > 0
select new { Type = type, Attributes = attributes.Cast<SomeAttribute>() })
.ToList();
Run Code Online (Sandbox Code Playgroud)
这很简单,可以扩展到方法级别
var methodsWithAttributes =
(from assembly in AppDomain.CurrentDomain.GetAssemblies()
from type in assembly.GetTypes()
from method in type.GetMethods()
let attributes = method.GetCustomAttributes(typeof(SomeAttribute), true)
where attributes != null && attributes.Length > 0
select new { Type = type, Method = method,
Attributes = …Run Code Online (Sandbox Code Playgroud) c# ×3
attributes ×2
reflection ×2
.net ×1
constructor ×1
inheritance ×1
performance ×1
vb.net ×1