对象初始化器

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_39306736/article/details/79951344
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;


namespace _1_对象初始化器
{
    class Program
    {
        static void Main(string[] args)
        {
            //1)手动初始化Person实例的两个属性
            Person p1 = new Person();
            p1.Name = "lt1";
            p1.Age = 24;


            //2)使用构造函数进行初始化
            Person p2 = new Person("lt1", 24);


            //3)使用对象初始化器进行初始化
            Person p3 = new Person()
            {
                Name = "lt1",
                Age = 24
            };


            //4)对象初始化器的好处是用在集合初始化器中,在创建SqlParameter的时候使用的比较多
            List<Person> list = new List<Person>
            {
                new Person(){Name="lt1",Age=24},
                new Person(){Name="lmy1",Age=23}
            };
        }
    }


    class Person
    {
        private string _name;
        private int _age;


        public Person()
        {


        }


        public Person(string name, int age)
        {
            this.Name = name;
            this.Age = age;
        }


        public int Age
        {
            get { return _age; }
            set { _age = value; }
        }


        public string Name
        {
            get { return _name; }
            set { _name = value; }
        }
    }
}

猜你喜欢

转载自blog.csdn.net/qq_39306736/article/details/79951344