相关疑难解决方法(0)

何时自定义属性的构造函数运行?

什么时候运行?它是针对我应用它的每个对象运行的,还是只运行一次?它可以做任何事情,或者它的行为受到限制吗?

.net c# vb.net attributes constructor

73
推荐指数
3
解决办法
2万
查看次数

属性继承与反思

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

[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# reflection inheritance attributes custom-attributes

6
推荐指数
1
解决办法
487
查看次数

扫描自定义属性的所有类和方法的最佳实践

我有史以来第一次真正需要手动进行装配扫描.我遇到了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# reflection performance

5
推荐指数
1
解决办法
4416
查看次数