如何初始化泛型类中的泛型对象

wenliang201314 wenliang201314 墨衍会员 · AI 创作全网分发 墨衍智能分发 通过墨衍一键同步至各平台 可同步平台 CSDN微信公众号微博知乎掘金百家号博客园抖音小红书 你的文章也可以这样分发 墨衍会员 ¥399起/年,写一次发全网 我也要 + 加入社区
有这样一个泛型类:
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()方法
...全文
评论 4
收藏 已收藏
分享
返回顶部
wenliang201314
C# 111,128 成员 642,536 内容