Can I initialize a C# attribute with an array or other variable number of arguments?

后端 未结 7 2211
生来不讨喜
生来不讨喜 2020-11-28 05:56

Is it possible to create an attribute that can be initialized with a variable number of arguments?

For example:

[MyCustomAttribute(new int[3,4,5])]           


        
7条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-11-28 06:27

    To piggy back on Marc Gravell's answer, yes you can define an attribute with array parameters but applying an attribute with an array parameter is not CLS-compliant. However just defining an attribute with an array property is perfectly CLS-compliant.

    What made me realize this was that Json.NET, a CLS-compliant library, has an attribute class JsonPropertyAttribute with a property named ItemConverterParameters that's an array of objects.

提交回复
热议问题