记录使用对象初始值设定项初始化对象。
using System; using System.Collections.Generic; namespace ConsoleApp2 { class Program { static void Main(string[] args) { // 使用构造函数初始化对象 StudentName student1 = new StudentName("Craig", "Playstead"); // 以声明方式初始化类型对象,调用默认构造函数,默认构造函数必须为public StudentName student3 = new StudentName { ID = 183 }; // 以声明方式初始化类型对象,调用默认构造函数,默认构造函数必须为public StudentName student4 = new StudentName { FirstName = "Craig", LastName = "Playstead", ID = 116 }; // 对象初始值设定项可用于在对象中设置索引器 var team = new BaseballTeam { [4] = "Jose Altuve", ["RF"] = "Mookie Betts", ["CF"] = "Mike Trout" }; Console.WriteLine(team["2B"]); } } public class StudentName { // 如果私有,则无法以声明方式初始化类型对象 public StudentName() { } public StudentName(string first, string last) { FirstName = first; LastName = last; }
public string FirstName { get; set; } public string LastName { get; set; } public int ID { get; set; } public override string ToString() => FirstName + " " + ID; } public class BaseballTeam { private string[] players = new string[9]; private readonly List<string> positionAbbreviations = new List<string> { "P", "C", "1B", "2B", "3B", "SS", "LF", "CF", "RF" }; public string this[int position] { // Baseball positions are 1 - 9. get { return players[position - 1]; } set { players[position - 1] = value; } } public string this[string position] { get { return players[positionAbbreviations.IndexOf(position)]; } set { players[positionAbbreviations.IndexOf(position)] = value; } } } }