属性错误:属性参数必须是属性参数类型的常量表达式,typeof表达式或数组创建表达式

Jag*_*ggu 3 .net c#

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

[MyAtt(Someproperty = 
            Enums.SecurityRight.A.ToString() + "&" + (Enums.SecurityRight.B.ToString() ))]
Run Code Online (Sandbox Code Playgroud)

但是,这会给出错误:"属性参数必须是属性参数类型的常量表达式,typeof表达式或数组创建表达式"

我知道你只能传递常数.但是我怎么逃避这个呢?任何招数?

谢谢.

Han*_*ood 7

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

您可以使用const值.

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

[MyAtt(StringProperty = Enums.SecurityRight.A + "&" + Enums.SecurityRight.B)]
Run Code Online (Sandbox Code Playgroud)

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

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

[MyAtt(IntegerProperty = Enums.SecurityRight.A | Enums.SecurityRight.B)]
Run Code Online (Sandbox Code Playgroud)

编辑:IntegerProperty上面更改以接收多个值.

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