use decimal values as attribute params in c#?

2020-01-27 03:08发布

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

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

Thanks.

5条回答
贪生不怕死
2楼-- · 2020-01-27 03:35

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

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.

查看更多
够拽才男人
3楼-- · 2020-01-27 03:36

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

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

Edit: I know this is not convenient.

查看更多
家丑人穷心不美
4楼-- · 2020-01-27 03:43

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

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.

查看更多
萌系小妹纸
5楼-- · 2020-01-27 03:53

For realtime tricks with attributes i am using TypeConverter class.

查看更多
Viruses.
6楼-- · 2020-01-27 03:57

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.

查看更多
登录 后发表回答