开发者

Default value for attribute constructor?

I'm getting this error,

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

When I try to write something like this

[AttributeUsage(AttributeTargets.Method, AllowMultiple = false)]
public class UrlAttribute : Attribute
{
    public UrlAttribute(string pattern, string name=null)
    {
        // ...

It doesn't even show a line number, but it disappears when I take out that =null bit.

Actually, the err开发者_开发技巧or only occurs both when I provide a default value and rely on it (i.e., I omit it) like so

    [Url("/index")]

I'm curious to know why this? How is "null" not a constant expression?


I'm calling 'bug'.

I hope you don't mind, I reported the bug to Microsoft.

UPDATE:

I received the following feedback from Microsoft today, emphasis added.

Thanks for reporting this issue you've encountered with Visual Studio!

We've fixed up optional string parameters on attributes in our code. You'll see this fix in the version of Visual Studio after VS 2010.

Alex Turner

Program Manager

Visual Basic and C# Compiler


Attributes already provide default-able arguments. You simply create public properties on the attribute and those can be assigned in the attribute instantiation process. It already works, it's already well-understand and it's consistent with how framework attributes work. So...why not just use that mechanism instead of trying to redundantly add default parameters to the constructor?

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜