Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
359 views
in Technique[技术] by (71.8m points)

c# - An attribute argument must be a constant expression, ...- Create an attribute of type array

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?

question from:https://stackoverflow.com/questions/25859094/an-attribute-argument-must-be-a-constant-expression-create-an-attribute-of

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

This supplements the information Simon already gave.

I found some documentation here: Attribute parameter types:

The types of positional and named parameters for an attribute class are limited to the attribute parameter types, which are:

  • One of the following types: bool, byte, char, double, float, int, long, sbyte, short, string, uint, ulong, ushort.
  • The type object.
  • The type System.Type.
  • An enum type, provided it has public accessibility and the types in which it is nested (if any) also have public accessibility (Attribute specification).
  • Single-dimensional arrays of the above types. (emphasis added by me)

A constructor argument or public field which does not have one of these types, cannot be used as a positional or named parameter in an attribute specification.

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...