使用對象初始值設定項初始化


記錄使用對象初始值設定項初始化對象。

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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM