【问题标题】:Attribute error: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type属性错误:属性参数必须是属性参数类型的常量表达式、typeof表达式或数组创建表达式
【发布时间】:2011-12-05 20:02:10
【问题描述】:

我想将一些枚举列表传递给我的 Attribute 属性。但它很漂亮,你可以将 List 传递给 Attribute 的属性。所以我尝试将其转换为字符串表示并尝试执行以下操作:

[MyAtt(Someproperty = 
            Enums.SecurityRight.A.ToString() + "&" + (Enums.SecurityRight.B.ToString() ))]

但是,这会产生错误:“属性参数必须是属性参数类型的常量表达式、typeof 表达式或数组创建表达式”

我知道你只能传递常量。但我怎么能摆脱这个呢?有什么技巧吗?

谢谢。

【问题讨论】:

标签: c# .net


【解决方案1】:

如果我的 C# 编码关闭,请原谅我。我用的是VB。

您可以使用const 值。

namespace Enums {
    static class SecurityRight {
        const String A = "A";
        const String B = "B";
    }
}

[MyAtt(StringProperty = Enums.SecurityRight.A + "&" + Enums.SecurityRight.B)]

如果属性接受与枚举相同的数据类型,则可以使用enum

namespace Enums {
    [Flags()]
    enum int SecurityRight {
        A = 1;
        B = 2;
    }
}

[MyAtt(IntegerProperty = Enums.SecurityRight.A | Enums.SecurityRight.B)]

编辑:更改了上面的 IntegerProperty 以接收多个值。

属性是在编译时设置的,而不是在运行时设置的。通过使用ToString,您正在调用运行时使用的代码。您必须使用常量值。

【讨论】:

  • 不错,但不是我想要的。我正在寻找使用枚举的第二种方法。我想在 1 个属性中发送 2 个枚举。但是你只发了一个。 [MyAtt(IntegerProperty = Enums.SecurityRight.A)]
  • 这如何允许将值列表传递给属性?
  • @Jaggu,如果您想将它们作为字符串发送,则必须将它们作为字符串键入或找到其他不涉及函数调用的方式。如果要将组合值作为数字发送,可以使用Enum.A | Enum.B
  • @AdamRalph,直到现在我才明白列表在这种情况下的含义。如果属性需要该格式,则第一个代码块适用于列表。
  • 通过列表我的意思是我的属性中有一个List<Enums> enums;,我可以从消费者那里传递它。但这是不可能的。 Adam 提供的链接解决了可以使用参数传入数组的问题。
猜你喜欢
  • 2011-12-10
  • 1970-01-01
  • 1970-01-01
  • 2014-11-09
  • 2013-02-09
相关资源
最近更新 更多