VB.net 2010 视频教程 VB.net 2010 视频教程 python基础视频教程
SQL Server 2008 视频教程 c#入门经典教程 Visual Basic从门到精通视频教程
当前位置:
首页 > Python基础教程 >
  • 使用对象初始值设定项初始化

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

复制代码
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; }
        }
    }
}
复制代码

 

量变会引起质变。

相关教程