Initialize the int type set, and write as follows:
static void Main(string[] args) { var list = new List<int> {0, 1}; foreach (var item in list) { Console.WriteLine(item); } Console.ReadKey(); }
Initialize the key-value pair set, and write as follows:
static void Main(string[] args) { var dic = new Dictionary<string, string> { {"location", "qingdao"}, {"street","lingchuang"} }; foreach (var item in dic) { Console.WriteLine("{0}:{1}", item.Key, item.Value); } Console.ReadKey(); }
How does the compiler "read" The set initializer?
-- The compiler understands the set initializer according to the Convention, that is, if a type implements the ienumerable <t> interface and provides the add (Object OBJ) method, you can use the set initialization tool for this type.
Suppose we want to define a set of models through a set initiator, and use bust, waist circumference, and hip circumference as the parameters of the Set initiator:
var list = new MoTes{ {79, 60, 89}, {82, 63, 90}};
Like the int type, {79, 60, 89} is a data structure that defines it as a structure type:
Public struct Sanwei {public readonly double _ Xiong; Public readonly double _ Yao; Public readonly double _ Tun; // The parameter type, sequence, and quantity of the constructor determine the parameter type, sequence, and quantity of the Set initiator. Public Sanwei (double Xiong, double Yao, double Tun) {_ Xiong = Xiong; _ Yao = Yao; _ Tun = Tun ;}}
To enable the motes class to use the set initiator, two conditions must be met:
1. Implement the ienumerable <Sanwei> Interface
2. The add (double Xiong, double Yao, double Tun) method is provided.
public class MoTes : IEnumerable<SanWei> { private readonly List<SanWei> _motes; public MoTes() { _motes = new List<SanWei>(); } public void Add(double xiong, double yao, double tun) { _motes.Add(new SanWei(xiong, yao, tun)); } public IEnumerator<SanWei> GetEnumerator() { return _motes.GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } }
On the client:
Static void main (string [] ARGs) {var list = new motes () {79, 60, 89}, {82, 63, 90 }}; foreach (VAR item in list) {console. writeline ("Bust: {0}, waist circumference: {1}, hip circumference: {2}", item. _ Xiong, item. _ Yao, item. _ Tun);} console. readkey ();}