使用对象初始值设定项初始化

可紊 提交于 2020-04-01 02:30:22

记录使用对象初始值设定项初始化对象。

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; }
        }
    }
}

 

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!