对象初始值设定和集合初始值设定

Posted HepburnXiao

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了对象初始值设定和集合初始值设定相关的知识,希望对你有一定的参考价值。

直接上代码:

    class Program
    {
        static void Main(string[] args)
        {
            StudentName student1 = new StudentName("Craig", "Playstead");

            //对象初始值设定必须先访问默认的实例构造函数
            //使用对象初始值设定项初始化对象
            StudentName student2 = new StudentName
            {
                FirstName = "Craig",
                LastName = "Playstead"
            };
            StudentName student3 = new StudentName
            {
                ID = 183
            };
            StudentName student4 = new StudentName
            {
                FirstName = "Craig",
                LastName = "Playstead",
                ID = 116
            };
            Console.WriteLine(student1.ToString());
            Console.WriteLine(student2.ToString());
            Console.WriteLine(student3.ToString());
            Console.WriteLine(student4.ToString());
            Console.WriteLine();

            //使用集合初始值设定项初始化字典
            Dictionary<int, StudentName> students = new Dictionary<int, StudentName>()
            {
                {111,new StudentName {FirstName="Sachin",LastName ="Karnik",ID =211 } },
                {112, new StudentName {FirstName ="Dina",LastName ="Salimzianova",ID =317 } },
                {113, new StudentName {FirstName ="Andy",LastName ="Ruth",ID=198 } }

            };
           
            //字典的使用举例
            //foreach (KeyValuePair<int, StudentName> s in students)
            //{
            //    Console.WriteLine(s.Value .FirstName +"  "+s.Value .LastName +"  "+s.Value .ID );
            //}

            Dictionary<int, StudentName>.KeyCollection keys = students.Keys;
            foreach (int s in keys )
            {
                Console.WriteLine(students[s].ToString());
            }
            Console.ReadKey();
        }
    }
    public class StudentName
    {
        //如果这是默认构造函数是private,那么对象初始值设定将会报错
        public StudentName ()
        {
            FirstName = "Lily";
        }
        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()
        {
            return FirstName + "  " +LastName +"  "+ ID;
        }
    }

  

 

以上是关于对象初始值设定和集合初始值设定的主要内容,如果未能解决你的问题,请参考以下文章

如何从对的初始值设定项列表构造对象?

字段初始值设定项无法引用非静态字段、方法或属性

字段初始值设定项无法引用非静态字段、方法或属性

为啥 C# 3.0 对象初始值设定项构造函数括号是可选的?

TypeScript是否支持带有对象初始值设定项的构造函数?

TypeScript - 对象初始值设定项中的 Get 属性问题