An attribute argument must be a constant expression, …- Create an attribute of type array

坚强是说给别人听的谎言 提交于 2019-11-26 18:57:49

This supplements the information Simon already gave.

I found some documentation here: Attributes Tutorial. (It says Visual Studio .NET 2003 at the top, but it still applies.)

Attribute parameters are restricted to constant values of the following types:

  • Simple types (bool, byte, char, short, int, long, float, and double)
  • string
  • System.Type
  • enums
  • object (The argument to an attribute parameter of type object must be a constant value of one of the above types.)
  • One-dimensional arrays of any of the above types (emphasis added by me)

The last bullet point explains your syntax error. You've defined a one-dimensional array, but it should only be of primitive types, string, etc. as listed in the previous bullet points.

Attribute arguments must be compile-time constant. That means that the compiler must be able to "bake in" the values of the arguments when the assembly is compiled. new ReferenceType() is not constant - it must be evaluated at runtime to determine what it is.

Interestingly, this is a little bit flimsy in that there are some edge cases to that rule. Other than those though, you cannot do what you're trying to do.

Let me add that the compiler can return this error without any particular file or line of code, if your attribute has a constructor that has a parameter that isn't a simple type and you use the constructor (i.e. your non-simple parameter has a default value).

[MyAttribute(MySimpleParameter: "Foo")]
public class MyObject
{

}

public class MyAttribute : Attribute
{
    public string MySimpleProperty { get; set; }

    public MyPropertyClass MyComplexProperty { get; set; }

    public MethodAttribute(string MySimpleParameter, MyPropertyClass MyComplexParameter = null)
    {
        MySimpleProperty = MySimpleParameter;
        MyComplexProperty = MyComplexParameter;
    }
}

public class MyPropertyClass
{
    public string Name { get; set; }
    public string Method { get; set; }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!