AssemblyInfo和自定义属性

时间:2016-02-17 10:18:46

标签: c# asp.net-mvc assemblyinfo

我想向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添加自定义属性的最佳方法。我似乎无法找到获取属性值的正确方法。

1 个答案:

答案 0 :(得分:6)

您需要提供一个公开会员,公开您想要展示的内容:

[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)