Any collection that has a method Add()and implements IEnumerablecan be initialized this way. See Initializers of objects and collections for C # for more details . (The absence of a new call Collection<T>is due to the object initializer, and the ability to add inline elements is associated with the collection initializer.)
Add() .
, :
using System;
using System.Collections.ObjectModel;
class Test
{
public Test()
{
this.Collection = new Collection<int>();
}
public Collection<int> Collection { get; private set; }
public static void Main()
{
Test test = new Test
{
Collection = { 3, 4, 5 }
};
foreach (var i in test.Collection)
{
Console.WriteLine(i);
}
Console.WriteLine("Press any key to exit...");
Console.ReadKey();
}
}