Why “decimal” is not a valid attribute parameter type?

后端 未结 3 1098
名媛妹妹
名媛妹妹 2020-11-29 22:30

It is really unbelievable but real. This code will not work:

[AttributeUsage(AttributeTargets.Property|AttributeTargets.Field)]
public class Range : Attribut         


        
3条回答
  •  栀梦
    栀梦 (楼主)
    2020-11-29 23:12

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

    Taken from this answer by 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.

提交回复
热议问题