欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

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

程序员文章站 2022-04-27 18:38:40
记录使用对象初始值设定项初始化对象。 using System; using System.Collections.Generic; namespace ConsoleApp2 { class Program { static void Main(string[] args) { // 使用构造函数 ......

记录对象。

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