C#中我接触到的几中初始化器.

来源:互联网 发布:ubuntu 安装openjdk 8 编辑:程序博客网 时间:2024/05/31 19:04

直接上代码:

using System;using System.Collections.Generic;using System.Linq;using System.Text;namespace Csharp3._0初始化器{    class Program    {        public class People        {            public People()            {            }            public People(string name)            {                Name = name;            }            public string Name { get; set; }            public int Age { get; set; }            public string Sex { get; set; }            public override string ToString()            {                //return base.ToString();                return ((Name == null || Name == string.Empty) ? "string.Empty" : Name) + "_" + Age.ToString() + "_" + ((Sex == null || Sex == string.Empty) ? "string.Empty" : Sex);            }        }        static void Main(string[] args)        {            //1、对象初始化器,在调用构造函数的时候没有加"()"的,前提是,必须有午餐的构造函数            People p1 = new People { Name = "name", Age = 21, Sex = "男" };//这个是初始化了【所有】属性.            Console.WriteLine("p1--->" + p1.ToString() + System.Environment.NewLine);            People p2 = new People { Age = 34, Sex = "女" };               //这个仅仅初始化【两个】属性.            Console.WriteLine("p2--->" + p2.ToString() + System.Environment.NewLine);            /*--------------------------------分割线--------------------------------*/            //2、集合初始化器            List<People> pList = new List<People> {                                 new People { Name = "Name_1", Sex = "男", Age = 12 },                                 new People { Name = "Name_2", Sex = "男", Age = 33 },                                 new People { Name = "Name_3", Sex = "男", Age = 25 }                                 };            foreach (People p in pList)            {                Console.WriteLine("---->" + p.ToString());            }            Console.WriteLine(System.Environment.NewLine);            //这样在你知道需要添加的对象的时候,就不用反复调用【Add】方法了.            //不过据说编译器在遇到这样的代码时,还是会自己调用Add方法  *_*!!!            /*--------------------------------分割线--------------------------------*/            //3、对象初始化器还可以结合构造函数一起使用            //例子:            People p3 = new People("name") { /*Age = 21,*/ Sex = "男" };            Console.WriteLine("p3--->" + p3.ToString() + System.Environment.NewLine);            Console.ReadKey();        }    }}


另外这次测试,还解决了我一个问题,就是对于int类型,如果没有显示的初始化,编译器会自动初始化为0.

 

再补充下,刚刚我看到别人写的一个博客,比我的全些,其中有一段我测试的时候还真没注意到,我吧哪位的原话贴下来,分享下:

 

构造函数赋值和初始化构造器赋值那个最先被执行?

比如下述代码,结果是那个呢??

static void Main(string[] args)
{
    var cookie = new  System.Net.Cookie("MyCookie", "Jose") { Name = "test02", Comment = "a  cookie" };
    Console.WriteLine(cookie.Name);
     Console.ReadLine();
}

答案:

构造函数比初始化构造器更早被执行。

上述WriteLine 写出来的信息为:test02

 

原创粉丝点击