为什么是“十进制"?不是有效的属性参数类型?

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.

这篇关于为什么是“十进制"?不是有效的属性参数类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

DispatcherQueue null when trying to update Ui property in ViewModel(尝试更新ViewModel中的Ui属性时DispatcherQueue为空)
Drawing over all windows on multiple monitors(在多个监视器上绘制所有窗口)
Programmatically show the desktop(以编程方式显示桌面)
c# Generic Setlt;Tgt; implementation to access objects by type(按类型访问对象的C#泛型集实现)
InvalidOperationException When using Context Injection in ASP.Net Core(在ASP.NET核心中使用上下文注入时发生InvalidOperationException)
LINQ many-to-many relationship, how to write a correct WHERE clause?(LINQ多对多关系,如何写一个正确的WHERE子句?)