当前位置: 移动技术网 > IT编程>开发语言>c# > 使用对象初始值设定项初始化

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

2020年04月01日  | 移动技术网IT编程  | 我要评论

记录对象。

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

 

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网