属性参数必须是一个常量表达式,...-创建类型为array的属性 [英] 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:
属性参数必须是属性参数类型的常量表达式,typeof表达式或数组创建表达式
An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type
为什么会发生此错误?
推荐答案
这补充了Simon已经给出的信息。
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:
- 以下类型之一:bool,byte ,char,double,float,int,long,sbyte,short,string,uint,ulong,ushort。
- T他键入对象。
- 类型System.Type。
- 枚举类型,只要它具有公共可访问性并且嵌套在其中(
- 上述类型的一维数组。 (由我添加的重点)
- 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.
这篇关于属性参数必须是一个常量表达式,...-创建类型为array的属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!