问题
Here is my custom attribute and a class I\'m using it on:
[MethodAttribute(new []{new MethodAttributeMembers(), new MethodAttributeMembers()})]
public class JN_Country
{
}
public class MethodAttribute : Attribute
{
public MethodAttributeMembers[] MethodAttributeMembers { get; set; }
public MethodAttribute(MethodAttributeMembers[] methodAttributeMemberses)
{
MethodAttributeMembers = methodAttributeMemberses;
}
}
public class MethodAttributeMembers
{
public string MethodName { get; set; }
public string Method { get; set; }
public string MethodTitle { get; set; }
}
The syntax error, displayed on the first line above:
An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type
Why does this error occur?
回答1:
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.
回答2:
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; }
}
来源:https://stackoverflow.com/questions/25859094/an-attribute-argument-must-be-a-constant-expression-create-an-attribute-of