Custom Assembly Attributes

↘锁芯ラ 提交于 2019-11-26 10:31:04

问题


I would like to know if I can define custom assembly attributes. Existing attributes are defined in the following way:

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

Is there a way I can do the following:

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

回答1:


Yes you can. We do this kind of thing.

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

To read use this kind of linq stmt.

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



回答2:


Yes, use AttributeTargets.Assembly:

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


来源:https://stackoverflow.com/questions/1936953/custom-assembly-attributes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!