【问题标题】:Set custom attribute value from Enum in C#在 C# 中从 Enum 设置自定义属性值
【发布时间】:2021-11-23 20:46:12
【问题描述】:

我有一个自定义属性,如下所示,

   [AttributeUsage(AttributeTargets.All, Inherited = true, AllowMultiple = false)]
    public class SetValForAll : Attribute
    {
        public string Limit { get; set; }

        public SetValForAll(string limit)
        {
            Limit = limit;
        }
    }

在使用此属性(SetValForAll)时,我想使用一个枚举传递 Limit 的值,但它显示错误“属性参数必须是常量表达式、typeof 表达式或数组创建表达式一个属性参数类型'

我的枚举如下,

        public enum LimitEnum
        {
            max,
            min
        }

以下代码在属性行中抛出错误。

[SetValForAll(LimitEnum.max.ToString())]
public class UsingTheAttributeHere
{
}

如何在使用 SetValForAll 属性时从 LimitEnum 中获取值,而不是传递硬编码字符串?

【问题讨论】:

    标签: c# .net enums attributes


    【解决方案1】:

    您可以使用nameof 表达式将enum 作为字符串常量:

    [SetValForAll(nameof(LimitEnum.max))]
    

    (Reference.)

    【讨论】:

    • 最好将名称作为常量字符串传递。
    • 谢谢@stenehr。有用。我已将您的答案标记为已接受
    【解决方案2】:

    好吧,你不能在属性值中传递非常量字符串。为什么不使用enum 类型而不是string 作为您的属性?可以使用LimitEnum 传入构造函数。

       [AttributeUsage(AttributeTargets.All, Inherited = true, AllowMultiple = false)]
        public class SetValForAll : Attribute
        {
        public LimitEnum Limit { get; set; }
    
        public SetValForAll(LimitEnum limit)
        {
            Limit = limit;
        }
        }
    

    并像这样使用它:

    [SetValForAll(LimitEnum.max)]
    

    【讨论】:

    • 为您解答。这可能是更好的选择。谢谢你的建议
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-10-26
    • 1970-01-01
    • 1970-01-01
    • 2021-07-21
    • 1970-01-01
    相关资源
    最近更新 更多