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

时间:2014-09-16 00:50:47

标签: c# custom-attributes

这是我的自定义属性和我在其上使用的类:

[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表达式或数组创建表达式

为什么会出现此错误?

3 个答案:

答案 0 :(得分:27)

这补充了西蒙已经提供的信息。

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

  

属性参数仅限于以下类型的常量值:

     
      
  • 简单类型(bool,byte,char,short,int,long,float和double)
  •   
  • 字符串
  •   
  • 的System.Type
  •   
  • 枚举
  •   
  • object(对象类型的属性参数的参数必须是上述类型之一的常量值。)
  •   
  • 上述任何一种类型的一维数组 (我强调添加)
  •   

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

答案 1 :(得分:16)

属性参数必须是编译时常量。这意味着编译器必须能够"烘烤"编译程序集时参数的值。 new ReferenceType()不是常量 - 必须在运行时对其进行评估以确定它是什么。

有趣的是,this is a little bit flimsy因为该规则存在一些边缘情况。除此之外,你不能做你想做的事。

答案 2 :(得分:0)

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

[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; }
}
相关问题