Changing size of array in extension method does not work?

前端 未结 3 740
别那么骄傲
别那么骄傲 2021-01-14 21:49

So basically I wrote my little Add extension method for array types.

using System;
using System.Linq;
public static class Extensions 
{
    publ         


        
3条回答
  •  说谎
    说谎 (楼主)
    2021-01-14 22:08

    You may change code like this:

    public static class Extensions 
    {
        public static T[] Add(this T[] _self, T item)
        {
            return _self.Concat(new T[] { item }).ToArray();
        }
    }
    public class Program
    {
        public static void Main()
        {
            string[] test = { "Hello" };
            test = test.Concat(new string[] { "cruel" }).ToArray();
            test = test.Add("but funny");
            Console.WriteLine(String.Join(" ", test) + " world");
        }
    }
    

    As a side note - usage will be same as Concat method.

提交回复
热议问题