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


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

    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; } } } }
  • 相关阅读:
    一个经典的多线程同步问题
    原子操作 Interlocked系列函数
    C中的volatile用法
    android值类型转换
    Button事件的三种实现方法
    【Android UI】顶部or底部菜单的循环滑动效果一
    【Android UI】侧滑栏的使用(HorizontalScrollView控件的使用)
    Android问题解决
    【Android UI】自定义带按钮的标题栏
    Android 设置 横屏 竖屏
  • 原文地址:https://www.cnblogs.com/bibi-feiniaoyuan/p/12609296.html
Copyright © 2020-2023  润新知