在.net中的泛型讲解(一)说明了泛型中的代码的重用性,在第二这里我们用代码去说明泛型的扩展性,我们可以扩展类型T,在任何时候,如果需求发生了变化,又要以不同的格式来输出ID。我们甚至可以扩展一个ID类。然后用ID类来替换T。
static void Main(string[] args)
{
MyID myId = new MyID("北海", "生态", "三班", "0001");
Person<MyID> personID = new Person<MyID>(myId, "猫哥", "猫");
Console.WriteLine("ID:{0},名字:{1},姓:{2}", myId.City + "-" + myId.School + "-" + myId.ClassName + "-" + myId.Number, personID.FirstName, personID.LastName);
}
public class Person<T>
{
private T _t;
public T T1
{
get { return _t; }
set { _t = value; }
}
private string _firstName;
public string FirstName
{
get { return _firstName; }
set { _firstName = value; }
}
private string _lastName;
public string LastName
{
get { return _lastName; }
set { _lastName = value; }
}
public Person() { }
public Person(T t1, string firstName, string lastName)
{
this._t = t1;
this._firstName = firstName;
this._lastName = lastName;
}
}
public class MyID
{
private string _city;
public string City
{
get { return _city; }
set { _city = value; }
}
private string _school;
public string School
{
get { return _school; }
set { _school = value; }
}
private string _className;
public string ClassName
{
get { return _className; }
set { _className = value; }
}
private string _number;
public string Number
{
get { return _number; }
set { _number = value; }
}
public MyID() { }
public MyID(string city, string school, string className, string number)
{
this._city = city;
this._school = school;
this._className = className;
this._number = number;
}
}
当然有人会说,你这里泛型可以做到的,我们用object也同样可以做到,是的,这里泛型可以做到的,object也同样可以做到。但是......(想知道为什么的小伙伴,可以自己去探索)