如何初始化泛型类中的泛型对象
有这样一个泛型类:
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()方法
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()方法
...全文
相关推荐
Java中的泛型详解
然而,通过类型转换,我们可以在运行时检查对象的实际类型,尽管不能直接修改泛型容器的类型。
C#泛型学习
#### 五、泛型中的类型约束有时候,我们希望限制泛型参数的类型范围,比如只允许特定类型的对象被存储。可以通过在类型参数后添加约束来实现这一点。常见的约束包括:1.
java泛型实例讲解代码.rar
**泛型接口**: 类似于泛型类,泛型接口也可以包含类型参数。
C#基础之泛型
泛型的主要目标是提供类型安全、高效的数据容器,避免了不必要的装箱拆箱操作,从而提升了性能。本文将深入探讨C#中的泛型基础,包括泛型的本质、规范以及如何通过反射来创建泛型实例。1.
C#中的where泛型约束介绍
在C#中,泛型是一种强大的工具,它允许我们编写可重用的代码,这些代码可以处理多种数据类型。泛型约束则是对泛型类型参数的一种限制,确保在使用泛型类、方法或其他泛型结构时,传入的类型必须符合特定条件。


