1

在 C# 中我可以写

var y = new List<string>(2) { "x" , "y" };

List“x”和“y”初始化一个。

如何声明一个类以接受这种初始化语法?

我的意思是,我想写:

var y = new MyClass(2, 3) { "x" , "y" };
4

4 回答 4

6

查看 C# 规范的第 7.6.10.3 节:

应用集合初始值设定项的集合对象必须是实现 System.Collections.IEnumerable 的类型,否则会发生编译时错误。对于按顺序指定的每个指定元素,集合初始化程序调用目标对象的 Add 方法,并将元素初始化程序的表达式列表作为参数列表,对每个调用应用正常的重载决策。因此,集合对象必须包含适用于每个元素初始值设定项的 Add 方法。

一个非常简单的例子:

   class AddIt : IEnumerable
   {
      public void Add(String foo) { Console.WriteLine(foo); }

      public IEnumerator GetEnumerator()
      {
         return null; // in reality something else
      }
   }

   class Program
   {
      static void Main(string[] args)
      {
         var a = new AddIt() { "hello", "world" };

         Console.Read();
      }
   }

这将在控制台打印“hello”,然后是“world”。

于 2012-12-06T19:36:53.077 回答
1

我不确定 (2,3) 应该表示什么。我知道这是您在第一行的收藏大小。您可以简单地从 List 或您需要模仿的任何结构继承。

刚刚在 LinqPad 中测试了这个示例:

void Main()
{
    var list = new Foo{
        "a",
        "b"
    };

    list.Dump();
}

class Foo : List<string>{ }
于 2012-12-06T19:44:36.233 回答
0

只需使用以下语法初始化类的字段:

// ...

Car myCar1 = new Car () { Model = "Honda", YearBuilt=2009 };
Car myCar2 = new Car () { Model = "Toyota", YearBuilt=2011 };

// ...

public class Car {

    public string Model;
    public int YearBuilt;
}
于 2012-12-06T19:35:54.177 回答
0

正如 Marcus 所指出的,该类必须实现IEnumerable接口并具有Add()调用者可以访问的方法。

简而言之,这个骨架示例将起作用:

public class MyClass : IEnumerable
{
    public void Add(string item)
    {

    }

    public IEnumerator GetEnumerator()
    {
        throw new NotImplementedException();
    }
}
于 2012-12-06T19:41:54.690 回答