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

后端 未结 7 2175
生来不讨喜
生来不讨喜 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:45

    You can do it, but it isn't CLS compliant:

    [assembly: CLSCompliant(true)]
    
    class Foo : Attribute
    {
        public Foo(string[] vals) { }
    }
    [Foo(new string[] {"abc","def"})]
    static void Bar() {}
    

    Shows:

    Warning 1   Arrays as attribute arguments is not CLS-compliant
    

    For regular reflection usage, it may be preferable to have multiple attributes, i.e.

    [Foo("abc"), Foo("def")]
    

    However, this won't work with TypeDescriptor/PropertyDescriptor, where only a single instance of any attribute is supported (either the first or last wins, I can't recall which).

    0 讨论(0)
提交回复
热议问题