Auto-initializing C# lists

后端 未结 6 2144
有刺的猬
有刺的猬 2020-12-14 05:15

I am creating a new C# List (List). Is there a way, other than to do a loop over the list, to initialize all the starting values to 0?

6条回答
  •  误落风尘
    2020-12-14 06:20

    You can use the initializer:

    var listInt = new List {4, 5, 6, 7};
    var listString = new List {"string1", "hello", "world"};
    var listCustomObjects = new List {new Cat(), new Dog(), new Horse()};
    

    So you could be using this:

    var listInt = new List {0.0, 0.0, 0.0, 0.0};
    

    Otherwise, using the default constructor, the List will be empty.

提交回复
热议问题