AssemblyInfo 和自定义属性

AssemblyInfo and custom attributes

我想向 AssemblyInfo 添加自定义属性,并且我创建了一个名为 AssemblyMyCustomAttribute

的扩展 class
[AttributeUsage(AttributeTargets.Assembly)]
public class AssemblyMyCustomAttribute : Attribute
{
    private string myAttribute;

    public AssemblyMyCustomAttribute() : this(string.Empty) { }
    public AssemblyMyCustomAttribute(string txt) { myAttribute = txt; }
}

然后我在 AssemblyInfo.cs 中添加了对 class 的引用并添加了值

// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("My Project")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("My Project")]
[assembly: AssemblyMyCustomAttribute("testing")]
[assembly: AssemblyCopyright("Copyright ©  2016")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]

现在我想在剃须刀视图中获取值 ("testing")

我尝试了以下但没有成功:

@ViewContext.Controller.GetType().Assembly.GetCustomAttributes(typeof(AssemblyMyCustomAttribute), false)[0].ToString();

不确定这是否是向我的 AssemblyInfo 添加自定义属性的最佳方法。我似乎找不到获取属性值的正确方法。

您需要提供一个 public 成员来公开您要显示的内容:

[AttributeUsage(AttributeTargets.Assembly)]
public class AssemblyMyCustomAttribute : Attribute
{
    public string Value { get; private set; }

    public AssemblyMyCustomAttribute() : this("") { }
    public AssemblyMyCustomAttribute(string value) { Value = value; }
}

然后转换属性并访问成员:

var attribute = ViewContext.Controller.GetType().Assembly.GetCustomAttributes(typeof(AssemblyMyCustomAttribute), false)[0];

@(((AssemblyMyCustomaAttribute)attribute).Value)