开发者

Attribute error: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type

I want to pass some list of enums to my Attribute property. But it's pretty you can pass List to Attribute's property. So I tried co开发者_运维知识库nverting it to string representation and tried to do something like this:

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

However, this gives the error: "An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type"

I understand you can only pass constants. But how do I get away with this? Any tricks?

Thanks.


Please pardon me if my C# coding is off. I use VB.

You can use const values.

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

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

You can use an enum if the attribute accepts the same data type as an enum.

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

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

EDIT: Changed IntegerProperty above to receive multiple values.

Attributes are set at compile time, not at runtime. By using ToString, you are invoking code that is used in runtime. You must use a constant value.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜