gpt4 book ai didi

c# - 为什么 "decimal"不是有效的属性参数类型?

转载 作者:IT王子 更新时间:2023-10-29 03:33:22 24 4
gpt4 key购买 nike

这真是令人难以置信,但却是真实的。此代码将不起作用:

[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 不行。

最佳答案

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.

关于c# - 为什么 "decimal"不是有效的属性参数类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3192833/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com