【问题标题】:AssemblyInfo and custom attributesAssemblyInfo 和自定义属性
【发布时间】:2016-02-17 10:18:45
【问题描述】:

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

【问题讨论】:

  • "我似乎找不到正确的方法来获取属性的值"是什么意思?您希望这段代码做什么以及它实际做什么?
  • 我正在尝试获取 AssemblyMyCustomAttribute 的值,因此是最后两行代码。在我看来,我想显示属性的值,即“测试”
  • 我明白了,但是它有什么作用呢?第二行看起来你很接近,但我不知道.Value 应该做什么。另请参阅How to read assembly attributes
  • 它现在在视图中通过文本显示:MyProject.AssemblyInfoExtensions.AssemblyMyCustomAttribute(我已经编辑了主帖子,使用 .ToString() 而不是 .Value() 因为 Value 不是一种方法可用。我已经尝试了您链接中的代码,但是在设置属性值时它返回 null
  • 请重新发布您的答案@CodeCaster。它有效:)

标签: c# asp.net-mvc assemblyinfo


【解决方案1】:

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

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

【讨论】:

  • 谢谢。我马上试一试
  • 它只显示文本“....AssemblyMyCustomAttribute.Value”。在 Debug/Watch 中添加 attribute.Value,我得到无法将方法组“值”转换为非委托类型“对象”。你打算调用..
  • 创建该类的实例有效。 AssemblyMyCustomAttribue 属性 = 新的 AssemblyMyCustomAttribute()
  • 但是你正在实例化一个属性来仅传递一个字符串,这非常没用。显示的代码应该可以工作并从程序集的元数据中获取属性。
  • 我意识到这篇文章已有 8 个月的历史,但我遇到了与 KMAN 相同的问题,它也显示文本“...AssemblyMyCustomAttribute.Value”。问题是在示例中缺少一组括号。最后一行应为:@(((AssemblyMyCustomAttribute)attribute).Value)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-01-20
  • 2015-09-04
  • 1970-01-01
  • 1970-01-01
  • 2011-12-10
  • 2011-03-27
相关资源
最近更新 更多