为什么"十进制"不是一个有效的属性参数类型? [英] Why "decimal" is not a valid attribute parameter type?

查看:385
本文介绍了为什么"十进制"不是一个有效的属性参数类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这实在是令人难以置信的,但真正的。这code是行不通的:

  [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field)
公共类范围:属性
{
    公共小数最大{获得;组; }
    公共小数敏{获得;组; }
}

公共类项目
{
    [范围(最小值=0米,最大=千米)] //编译错误:'民'不是一个有效的命名特性参数,因为它不是一个有效的属性参数类型
    公共十进制总{获得;组; }
}
 

虽然这个作品:

  [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field)
公共类范围:属性
{
    公共双马克斯{获得;组; }
    公共双民{获得;组; }
}

公共类项目
{
    [范围(最小值= 0D,最大= 1000D)
    公共十进制总{获得;组; }
}
 

谁能告诉我,为什么双是OK,而小数则不是。

解决方案
  

这是一个CLR的限制。只要   原始常量或数组   原语可以用作属性   参数。之所以是一个   属性必须是连接codeD完全   元数据。这比一个不同   方法体是codeD在IL。   使用元数据只有严格限制   值的可使用的范围。   在CLR的当前版本,   元数据值限制为   原语,空,类型和阵列   原语(可能已经错过了一个小   一个)。

从<一个拍摄href="http://stackoverflow.com/questions/507528/use-decimal-values-as-attribute-params-in-c/507533#507533">this通过 JaredPar

答案
  

小数,而基本类型不是   原始类型并因此不能   再presented在元数据中其中prevents   它从一种属性参数。

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

While this works:

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

Who can tell me why double is OK while decimal is not.

解决方案

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).

Taken from this answer by 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.

这篇关于为什么&QUOT;十进制&QUOT;不是一个有效的属性参数类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆