【问题标题】:An attribute argument must be a constant expression, ...- Create an attribute of type array属性参数必须是常量表达式,...- 创建数组类型的属性
【发布时间】:2014-11-09 15:09:47
【问题描述】:

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

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

为什么会出现这个错误?

【问题讨论】:

    标签: c# custom-attributes


    【解决方案1】:

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

    我在这里找到了一些文档:Attribute parameter types:

    属性类的位置参数和命名参数的类型仅限于属性参数类型,它们是:

    • 以下类型之一:bool、byte、char、double、float、int、long、sbyte、short、string、uint、ulong、ushort。
    • 类型对象。
    • System.Type 类型。
    • 枚举类型,前提是它具有公共可访问性,并且它所嵌套的类型(如果有)也具有公共可访问性(属性规范)。
    • 上述类型的一维数组。 (重点由我添加)

    不具有这些类型之一的构造函数参数或公共字段不能用作属性规范中的位置参数或命名参数。

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

    【讨论】:

    • 奇怪的是 double 支持 decimal
    【解决方案2】:

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

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

    【讨论】:

      【解决方案3】:

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

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

      【讨论】:

      • 我试图使用静态字符串,但没有成功,所以我不得不切换到 const
      猜你喜欢
      • 2011-12-10
      • 2011-12-05
      • 1970-01-01
      • 1970-01-01
      • 2013-02-09
      相关资源
      最近更新 更多