C#类似实例的初始化语法

LMB*_*LMB 1 c#

在C#我可以写

var y = new List<string>(2) { "x" , "y" };
Run Code Online (Sandbox Code Playgroud)

得到一个List"x"和"y"初始化.

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

我的意思是,我想写:

var y = new MyClass(2, 3) { "x" , "y" };
Run Code Online (Sandbox Code Playgroud)

Mar*_*cus 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();
      }
   }
Run Code Online (Sandbox Code Playgroud)

这将打印"hello",然后打印到控制台的"world".