JavaScript spread syntax in C#

后端 未结 4 557
刺人心
刺人心 2021-01-01 10:26

Is there any implementation in C# like JavaScript\'s spread syntax?

var arr = new []{
   \"1\",
   \"2\"//...
};

Console.WriteLine(...arr);
4条回答
  •  走了就别回头了
    2021-01-01 11:03

    One trick to get a behavior similar to this (without reflection) is to accept params SomeObject[][] and to also define an implicit operator from SomeObject to SomeObject[]. Now you can pass a mixture of arrays of SomeObject and individual SomeObject elements.

    public class Item
    {
        public string Text { get; }
    
        public Item (string text)
        {
            this.Text = text;
        }
    
        public static implicit operator Item[] (Item one) => new[] { one };
    }
    
    public class Print
    {
        // Accept a params of arrays of items (but also single items because of implicit cast)
    
        public static void WriteLine(params Item[][] items)
        {
            Console.WriteLine(string.Join(", ", items.SelectMany(x => x)));
        }
    }
    
    public class Test
    {
        public void Main()
        {
            var array = new[] { new Item("a1"), new Item("a2"), new Item("a3") };
            Print.WriteLine(new Item("one"), /* ... */ array, new Item("two")); 
        }
    }
    

提交回复
热议问题