Why quot;decimalquot; is not a valid attribute parameter type?(为什么是“十进制?不是有效的属性参数类型?)
问题描述
这真的令人难以置信,但却是真实的.此代码将不起作用:
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.
这篇关于为什么是“十进制"?不是有效的属性参数类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:为什么是“十进制"?不是有效的属性参数类型?


基础教程推荐
- 经典 Asp 中的 ResolveUrl/Url.Content 等效项 2022-01-01
- 全局 ASAX - 获取服务器名称 2022-01-01
- 从 VS 2017 .NET Core 项目的发布目录中排除文件 2022-01-01
- 在 VS2010 中的 Post Build 事件中将 bin 文件复制到物 2022-01-01
- 错误“此流不支持搜索操作"在 C# 中 2022-01-01
- 将事件 TextChanged 分配给表单中的所有文本框 2022-01-01
- JSON.NET 中基于属性的类型解析 2022-01-01
- 如何动态获取文本框中datagridview列的总和 2022-01-01
- 是否可以在 asp classic 和 asp.net 之间共享会话状态 2022-01-01
- 首先创建代码,多对多,关联表中的附加字段 2022-01-01