gpt4 book ai didi

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

转载 作者:IT王子 更新时间:2023-10-29 04:06:15 27 4
gpt4 key购买 nike

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

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

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

An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type

为什么会出现这个错误?

最佳答案

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

我在这里找到了一些文档: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.

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

关于c# - 属性参数必须是常量表达式,...- 创建数组类型的属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25859094/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com