自定义属性:属性参数必须是常量表达式
Custom attribute: An attribute argument must be a constant expression
我定义了一个自定义 enum
DescriptionAttribute
(见我之前的问题:)
public class DescriptionWithValueAttribute : DescriptionAttribute
{
public Decimal Value { get; private set; }
public DescriptionWithValueAttribute(String description, Decimal value)
: base(description)
{
Value = value;
}
}
我的 enum
看起来像这样:
public enum DeviceType
{
[DescriptionWithValueAttribute("Set Top Box", 9.95m)]
Stb = 1,
}
编译时出现如下错误:
An attribute argument must be a constant expression, typeof expression
or array creation expression of an attribute parameter type
我也试过:[DescriptionWithValueAttribute("Set Top Box", (Decimal)9.95)]
有什么想法吗?
根据this article:
属性参数仅限于以下类型的常量值:
- 简单类型(bool、byte、char、short、int、long、float 和 double)
- 字符串
- System.Type
- 枚举对象(类型对象的属性参数的参数必须是上述类型之一的常量值。)
- 上述任何类型的一维数组
所以,你不能使用十进制。将其替换为 float 或 double。其他方式 - 将值存储为字符串并解析它。
我已将我的自定义 enum
DescriptionAttribute
更新为以下内容:
public class DescriptionWithValueAttribute : DescriptionAttribute
{
public Decimal Value { get; private set; }
public DescriptionWithValueAttribute(String description, Double value)
: base(description)
{
Value = Convert.ToDecimal(value);
}
}
它期望 Double
然后转换为 Decimal
,因为我需要最终值作为 Decimal
。按预期工作。
我定义了一个自定义 enum
DescriptionAttribute
(见我之前的问题:
public class DescriptionWithValueAttribute : DescriptionAttribute
{
public Decimal Value { get; private set; }
public DescriptionWithValueAttribute(String description, Decimal value)
: base(description)
{
Value = value;
}
}
我的 enum
看起来像这样:
public enum DeviceType
{
[DescriptionWithValueAttribute("Set Top Box", 9.95m)]
Stb = 1,
}
编译时出现如下错误:
An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type
我也试过:[DescriptionWithValueAttribute("Set Top Box", (Decimal)9.95)]
有什么想法吗?
根据this article:
属性参数仅限于以下类型的常量值:
- 简单类型(bool、byte、char、short、int、long、float 和 double)
- 字符串
- System.Type
- 枚举对象(类型对象的属性参数的参数必须是上述类型之一的常量值。)
- 上述任何类型的一维数组
所以,你不能使用十进制。将其替换为 float 或 double。其他方式 - 将值存储为字符串并解析它。
我已将我的自定义 enum
DescriptionAttribute
更新为以下内容:
public class DescriptionWithValueAttribute : DescriptionAttribute
{
public Decimal Value { get; private set; }
public DescriptionWithValueAttribute(String description, Double value)
: base(description)
{
Value = Convert.ToDecimal(value);
}
}
它期望 Double
然后转换为 Decimal
,因为我需要最终值作为 Decimal
。按预期工作。