自定义装配属性

时间:2009-12-20 20:38:48

标签: c# .net assemblies attributes

我想知道我是否可以定义自定义程序集属性。现有属性按以下方式定义:

[assembly: AssemblyTitle("MyApplication")]  
[assembly: AssemblyDescription("This application is a sample application.")]  
[assembly: AssemblyCopyright("Copyright © MyCompany 2009")]  

有没有办法可以做到以下几点:

[assembly: MyCustomAssemblyAttribute("Hello World! This is a custom attribute.")]

2 个答案:

答案 0 :(得分:85)

是的,你可以。我们做这件事。

[AttributeUsage(AttributeTargets.Assembly)]
public class MyCustomAttribute : Attribute {
    string someText;
    public MyCustomAttribute() : this(string.Empty) {}
    public MyCustomAttribute(string txt) { someText = txt; }
    ...
}

阅读使用这种linq stmt。

var attributes = assembly
    .GetCustomAttributes(typeof(MyCustomAttribute), false)
    .Cast<MyCustomAttribute>();

答案 1 :(得分:8)

是的,使用AttributeTargets.Assembly:

[AttributeUsage(AttributeTargets.Assembly)]
public class AssemblyAttribute : Attribute { ... }