我可以初始化数组或参数其他变量数量C#的属性? [英] Can I initialize a C# attribute with an array or other variable number of arguments?
本文介绍了我可以初始化数组或参数其他变量数量C#的属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
是否可以创建可与参数可变数量进行初始化属性?
例如:
[MyCustomAttribute(新INT [3,4,5])] //这不起作用
公共MyClass的...
解决方案
属性将一个数组。但如果你控制的属性,你也可以使用参数而不是(这是更好的消费者,IMO):
类MyCustomAttribute:属性{
公众诠释[]值{搞定;组; } 公共MyCustomAttribute(PARAMS INT []值){
this.Values =值;
}
}[MyCustomAttribute(3,4,5)]
MyClass类{}
您的数组创建语法恰好处于关机状态:
类MyCustomAttribute:属性{
公众诠释[]值{搞定;组; } 公共MyCustomAttribute(INT []值){
this.Values =值;
}
}[MyCustomAttribute(新INT [] {3,4,5})]
MyClass类{}
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])] // this doesn't work
public MyClass ...
解决方案
Attributes will take an array. Though if you control the attribute, you can also use parameters 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 { }
这篇关于我可以初始化数组或参数其他变量数量C#的属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文