问题描述
这真的令人难以置信,但却是真实的.此代码将不起作用:
It is really unbelievable but real. This code will not work:
[AttributeUsage(AttributeTargets.Property|AttributeTargets.Field)]
public class Range : Attribute
{
public decimal Max { get; set; }
public decimal Min { get; set; }
}
public class Item
{
[Range(Min=0m,Max=1000m)] //compile error:'Min' is not a valid named attribute argument because it is not a valid attribute parameter type
public decimal Total { get; set; }
}
虽然这有效:
[AttributeUsage(AttributeTargets.Property|AttributeTargets.Field)]
public class Range : Attribute
{
public double Max { get; set; }
public double Min { get; set; }
}
public class Item
{
[Range(Min=0d,Max=1000d)]
public decimal Total { get; set; }
}
谁能告诉我为什么 double 可以,而 decimal 不行.
Who can tell me why double is OK while decimal is not.
推荐答案
这是一个 CLR 限制.仅有的原始常量或数组原语可以用作属性参数.原因是一个属性必须完全编码在元数据.这不同于一个用 IL 编码的方法体.使用元数据只会严格限制可以使用的值的范围.在当前版本的 CLR 中,元数据值仅限于原语、null、类型和数组原语(可能错过了一个未成年人一).
This is a CLR restriction. Only primitive constants or arrays of primitives can be used as attribute parameters. The reason why is that an attribute must be encoded entirely in metadata. This is different than a method body which is coded in IL. Using MetaData only severely restricts the scope of values that can be used. In the current version of the CLR, metadata values are limited to primitives, null, types and arrays of primitives (may have missed a minor one).
取自 this 答案JaredPar.
基本类型不是小数原始类型,因此不能以元数据表示,可防止它不是一个属性参数.
Decimals while a basic type are not a primitive type and hence cannot be represented in metadata which prevents it from being an attribute parameter.
这篇关于为什么是“十进制"?不是有效的属性参数类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!