C#對象初始化器
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace 對象初始化器
{
class Program
{
static void Main(string[] args)
{
//第二種初始化
var s1 = new student("張三",23);
Console.WriteLine(s1.ToString());
//第一種初始化
var s2 = new student { name = "李四", age = 34 };
Console.WriteLine(s2.ToString());
//第三種
var s3 = new student("王五",30) { ID=1};
}
}
public class student
{
public string name { set; get; }
public int age { set; get; }
public int ID { set;get;}
//第一種構造函數
public student()
{
}
//第二種構造函數
public student(string Name, int Age)
{
name = Name;
age = Age;
}
//方法重載
public override string ToString()
{
return name + ":" + age.ToString();
}
}
}