如何初始化泛型类中的泛型对象
有这样一个泛型类:
class test<T> where T : IPerson
{
private T man;
public test()
{
//这里如何初始化man的实例??
}
public string GetName()
{
//这里如何调用man的GetName()方法??
}
public int GetAge()
{
//这里如何调用man的GetAge()方法??
}
}
IPerson为一接口,其下有三个类继承至它:Grandpa,Father,Son
interface IPerson {
int GetAge();
string GetName();
}
public class Grandpa : IPerson {
public int GetAge()
{
return 99;
}
public string GetName()
{
return "I am Grandpa";
}
}
class Father : IPerson {
public int GetAge()
{
return 40;
}
public string GetName()
{
return "I am Father";
}
}
class Son : IPerson {
public int GetAge()
{
return 20;
}
public string GetName()
{
return "I am Son";
}
}
我想这么调用泛型类:
test<Father> test = new test<Father>();
test.GetName(); //这里要求自动调用Father的GetName()方法
test.GetAge(); //这里要求自动调用Father的GetAge()方法