c# - 我可以为属性使用集合初始值设定项吗?

标签 c# attributes custom-attributes object-initializers collection-initializer

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:

  1. One of the following types: bool, byte, char, double, float, int, long, short, string.
  2. The type object.
  3. The type System.Type.
  4. 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).
  5. 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/

相关文章:

c# - SQL 服务器 FTS : possible to get information how/why rows were matched?

JavaScript:监听属性变化?

python - getattr 和 setattr 在嵌套子对象/链接属性上?

javascript - 如何从单选按钮获取 jquery 或 JS 中的自定义属性值?

jquery - 浏览器未观察到 data-* 的更改,CSS 属性选择器属性未呈现

c# - 如何将本地数据库上传到 Windows Azure?

c# - 如何为我的 AdomdConnection 设置连接超时?

c# - 初始化整数数组

attributes - 在 AngularDart 中包含 mustache 指令时,NgAttr 值最初为空

asp.net - 在 ASP.NET MVC 中构建自定义授权