Che*_*hen 129 .net c# attributes
这真的令人难以置信,但真实.此代码不起作用:
[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不是.
djd*_*d87 129
这是CLR限制.只有原始常量或基元数组可用作属性参数.原因是属性必须完全在元数据中编码.这与用IL编码的方法体不同.使用MetaData只会严格限制可以使用的值的范围.在当前版本的CLR中,元数据值仅限于基元,null,类型和基元数组(可能错过了次要基元).
基本类型的小数不是基本类型,因此不能在元数据中表示,以防止它成为属性参数.
Kob*_*obi 53
从规格:
属性类的位置和命名参数的类型仅限于属性参数类型,它们是:
- 其中以下类型:
bool,byte,char,double,float,int,long,sbyte,short,string,uint,ulong,ushort.- 类型
object.- 类型
System.Type.- 枚举类型,前提是它具有公共可访问性,并且嵌套类型(如果有)也具有公共可访问性(属性规范).
- 上述类型的一维阵列.