The concise way to initialize an array of reference type object

前端 未结 3 1180
猫巷女王i
猫巷女王i 2021-01-19 06:00

I wonder if there is better way to initialize an array of reference type object, like this.

Queue[] queues = new Queue[10];
for (int i         


        
相关标签:
3条回答
  • 2021-01-19 06:39

    I have the same answer - to use a loop. But you can make it as an extension method for general purpose:

        public static void Init<T>(this IList<T> array )
        {
            if (array == null) return;
    
            for (int i = 0; i < array.Count; i++)
                array[i] = Activator.CreateInstance<T>();
        }
    

    and the just call it:

            Queue<int>[] queues = new Queue<int>[10];
            queues.Init();
    
    0 讨论(0)
  • 2021-01-19 06:44

    No, there isn't. Just factor it out into a utility method:

    // CommonExtensions.cs
    public static T[] NewArray<T> (int length) where T : class, new ()
    {
        var result = new T[length] ;
        for (int i = 0 ; i < result.Length ; ++i)
             result[i] = new T () ;
        return result ;
    }
    
    // elsewhere
    var queues = Extensions.NewArray<Queue<int>> (10) ;
    
    0 讨论(0)
  • 2021-01-19 06:54

    You could use this:

    Enumerable.Range(0,10).Select(_=>new Queue<int>()).ToArray()
    

    But IMO your first example is perfectly fine too.

    0 讨论(0)
提交回复
热议问题