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

wenliang201314 2011-03-25 09:55:25
有这样一个泛型类:
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()方法
...全文
639 4 打赏 收藏 转发到动态 举报
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
wangwenzhuang 2011-03-25
  • 打赏
  • 举报
回复
class test<T> where T : IPerson
{
private T man;

public test()
{
//这里如何初始化man的实例??
man = (T)Activator.CreateInstance(typeof(T));
}

public string GetName()
{
//这里如何调用man的GetName()方法??
return man.GetName();
}

public int GetAge()
{
//这里如何调用man的GetAge()方法??
return man.GetAge();
}
}
wenliang201314 2011-03-25
  • 打赏
  • 举报
回复
知道了,只要这样定义泛型类就可以了:
class test<T> where T : IPerson,new()

这里new()指明了创建T的实例时应该使用
vrhero 2011-03-25
  • 打赏
  • 举报
回复
加new约束...

class test<T> where T : IPerson,new()

T man =new T();

man.GetName();

110,534

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • Web++
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧