可以不必为了给属性赋值而写很多的构造函数重载了。节约了代码量。
注:Test本身的构造函数会被执行,即Console.WriteLine("Test constructor");
using System;
using System.Collections;
using System.Linq;
using System.Text;
using System.Collections.Generic;
using System.Runtime.Serialization;
using System.Text.RegularExpressions;
namespace TestCS
{
public class Test
{
public int X;
public int Y;
public Test2 t;
public Test()
{
Console.WriteLine("Test constructor");
}
public override string ToString()
{
return X.ToString() + "," + Y.ToString() + "," + t.ToString();
}
}
public class Test2
{
public int Z;
public override string ToString()
{
return "In Test2--"+Z.ToString();
}
}
public class Progarm
{
public static void Main(string[] args)
{
Test t = new Test() { X = 1, Y = 2, t = new Test2() { Z = 3 } };
Console.WriteLine(t.ToString());
}
}
}