自定义程序集属性

66

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

[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.")]

1
对于任何好奇的人,AssemblyTitle等都位于assemblyattributes.cs中。这是源代码:https://referencesource.microsoft.com/#mscorlib/system/reflection/assemblyattributes.cs。 - mekb
2个回答

93

是的,你可以。我们经常这样做。

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

使用下面这种类型的linq语句来读取。

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

1
但是如何将其作为构建属性打补丁呢? - Sinaesthetic
@Sinaesthetic - 你是什么意思? - Preet Sangha
例如,一个构建服务器。要在其中打补丁的构建号,您可以执行类似于 dotnet build -c Release /p:BuildNumber={BUILD_NUMBER} 的操作,因此对于这样的内容,我希望能够执行 dotnet build -c Release /p:MyCustomAttribute=foo - Sinaesthetic
@Sinaesthetic,你能想办法将其作为构建属性打补丁吗? - mirind4
在csproj中添加属性,将构建命令中的参数从属性设置为: <_Parameter1>$(MyCustomAttribute) ``` - tjmoore

8

是的,使用 AttributeTargets.Assembly:

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接