属性参数必须是常量表达式,… – 创建类型为array的属性

这是我的自定义属性和我正在使用它的类:

[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; } } 

语法错误,显示在上面的第一行:

属性参数必须是属性参数类型的常量表达式,typeof表达式或数组创建表达式

为什么会出现此错误?

这补充了西蒙已经给出的信息。

我在这里找到了一些文档: Attributes Tutorial 。 (它在顶部显示Visual Studio .NET 2003,但它仍然适用。)

属性参数限制为以下类型的常量值:

  • 简单类型(bool,byte,char,short,int,long,float和double)
  • 系统类型
  • 枚举
  • object(对象类型的属性参数的参数必须是上述类型之一的常量值。)
  • 任何上述类型的一维数组 (重点由我添加)

最后一个要点解释了您的语法错误。 您已经定义了一维数组,但它应该只是原始类型,字符串等,如前面的项目符号所列。

属性参数必须是编译时常量。 这意味着编译器必须能够在编译程序集时“烘焙”参数的值。 new ReferenceType()不是常量 – 必须在运行时计算它以确定它是什么。

有趣的是, 这有点脆弱 ,因为该规则存在一些边缘情况。 除此之外,你不能做你想做的事。

让我补充说,编译器可以在没有任何特定文件或代码行的情况下返回此错误,如果您的属性具有不是简单类型的参数的构造函数并且您使用构造函数(即您的非简单参数具有默认值)。

 [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; } }