gpt4 book ai didi

c# - AssemblyInfo 和自定义属性

转载 作者:太空狗 更新时间:2023-10-29 21:26:52 29 4
gpt4 key购买 nike

我想向 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("")]

现在我想在 Razor View 中获取值(“测试”)

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

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

关于c# - AssemblyInfo 和自定义属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35453815/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com