在 C# 中使用十进制值作为属性参数?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/507528/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-04 06:07:54  来源:igfitidea点击:

use decimal values as attribute params in c#?

c#parametersattributesdecimal

提问by rjlopes

I've been trying to use decimal values as params for a field attribute but I get a compiler error.

我一直在尝试使用十进制值作为字段属性的参数,但出现编译器错误。

I found this blog post linksaying it wasn't possible in .NET to use then, does anybody know why they choose this or how can I use decimal params?

我发现这个博客文章链接说它不可能在 .NET 中使用,有谁知道他们为什么选择这个或者我如何使用十进制参数?

采纳答案by JaredPar

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

这是 CLR 限制。只有原始常量或原始数组可以用作属性参数。原因是属性必须完全在元数据中编码。这与用 IL 编码的方法体不同。使用 MetaData 只会严重限制可以使用的值的范围。在当前版本的 CLR 中,元数据值仅限于原语、空值、类型和原语数组(可能漏掉了一个次要的)。

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.

Decimals 而基本类型不是原始类型,因此不能在元数据中表示,这阻止了它成为属性参数。

回答by Avram

For realtime tricks with attributes i am using TypeConverterclass.

对于具有属性的实时技巧,我正在使用TypeConverter类。

回答by ckittel

When I have run into this situation, I ended up exposing the properties on the attribute as a Double, but inside the attribute treated them like Decimal. Far from perfect, but for the simple cases, it just might be what you need.

当我遇到这种情况时,我最终将属性上的属性公开为 Double,但在属性内部将它们视为 Decimal。远非完美,但对于简单的情况,它可能正是您所需要的。

回答by Sam Harwell

You can use the following constructor. When you have a decimal literal in C# code, the C# compiler emits a call to this constructor.

您可以使用以下构造函数。当您在 C# 代码中有十进制文字时,C# 编译器会发出对此构造函数的调用。

Decimal(Int32, Int32, Int32, Boolean, Byte)

Decimal(Int32, Int32, Int32, Boolean, Byte)

Edit: I know this is not convenient.

编辑:我知道这不方便。

回答by Stefan Steinegger

I have the same problem. I consider to use strings. This is not type-safe, but it's readable and I think we will be able to write valid numbers in strings :-).

我也有同样的问题。我考虑使用strings。这不是类型安全的,但它是可读的,我认为我们将能够在字符串中写入有效数字:-)。

class BlahAttribute : Attribute
{
  private decimal value;

  BlahAttribute(string number)
  {
    value = decimal.Parse(number, CultureInfo.InvariantCulture);
  }
}

[Blah("10.23")]
class Foo {}

It's not a beauty, but after considering all the options, it's good enough.

算不上美,但考虑了所有的选择后,已经足够好了。