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

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

    Attributes will take an array. Though if you control the attribute, you can also use params instead (which is nicer to consumers, IMO):

    class MyCustomAttribute : Attribute {
        public int[] Values { get; set; }
    
        public MyCustomAttribute(params int[] values) {
           this.Values = values;
        }
    }
    
    [MyCustomAttribute(3, 4, 5)]
    class MyClass { }
    

    Your syntax for array creation just happens to be off:

    class MyCustomAttribute : Attribute {
        public int[] Values { get; set; }
    
        public MyCustomAttribute(int[] values) {
            this.Values = values;
        }
    }
    
    [MyCustomAttribute(new int[] { 3, 4, 5 })]
    class MyClass { }
    

提交回复
热议问题