该语法能够在调用构造函数的同时设置公有的字段或者属性,可减少要提供的重载构造函数。
对象初始值设定项可同时用于实例化和初始化对象,但前提是自断和属性间没有依存关系。
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
class Contact
{
public string firstName;
public string lastName;
public DateTime dateOfBirth;
public override string ToString()
{
StringBuilder sb = new StringBuilder();
sb.AppendFormat("Name: {0} {1}\r\n", this.firstName, this.lastName);
sb.AppendFormat("Date of Birth: {0}\r\n", this.dateOfBirth);
return sb.ToString();
}
}
class Program
{
static void Main(string[] args)
{
//对象初始值设定项
//两种情况下,结果相同
Contact c1 = new Contact();
c1.firstName = "zhanzhan";
c1.lastName = "Lisa";
c1.dateOfBirth = new DateTime(1991, 10, 5);
Console.WriteLine(c1.ToString());
Contact c2=new Contact
{
firstName="zhanzhan",
lastName="Lisa",
dateOfBirth=new DateTime(1991,10,5)
};
Console.WriteLine(c2.ToString());
Console.Read();
}
}
}
输出示例:
来源:CSDN
作者:小老陈
链接:https://blog.csdn.net/weixin_45909963/article/details/103896263