组装信息和自定义属性

本文关键字:自定义属性 信息 | 更新日期: 2023-09-27 18:34:54

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

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

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

// 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的最佳方法。我似乎找不到获取属性值的正确方法。

组装信息和自定义属性

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

[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];
@(((AssemblyMyCustomAttribute)attribute).Value)