C# 中的属性可以与集合初始值设定项一起使用吗?
例如,我想执行如下操作:
[DictionaryAttribute(){{"Key", "Value"}, {"Key", "Value"}}]
public class Foo { ... }
我知道属性可以有命名参数,因为这看起来与对象初始值设定项非常相似,我想知道集合初始值设定项是否也可用。
最佳答案
更新: 抱歉我弄错了 - 传递自定义类型的数组是不可能的 :(
The types of positional and named parameters for an attribute class are limited to the attribute parameter types, which are:
- One of the following types: bool, byte, char, double, float, int, long, short, string.
- The type object.
- The type System.Type.
- An Enum type, provided it has public accessibility and the types in which it is nested (if any) also have public accessibility (Section 17.2).
- Single-dimensional arrays of the above types. source
来源:stackoverflow .
您可以声明传递一个自定义类型的数组:
class TestType
{
public int Id { get; set; }
public string Value { get; set; }
public TestType(int id, string value)
{
Id = id;
Value = value;
}
}
class TestAttribute : Attribute
{
public TestAttribute(params TestType[] array)
{
//
}
}
但是编译错误发生在属性声明上:
[Test(new[]{new TestType(1, "1"), new TestType(2, "2"), })]
public void Test()
{
}
关于c# - 我可以为属性使用集合初始值设定项吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6932581/