【发布时间】:2016-09-14 18:23:14
【问题描述】:
我有一个抽象类 Creature,它接受一个泛型类型参数,由另外两个类 Human 和 Spider 扩展。每个子类都定义了其父类的泛型。
我不知道如何将子类作为父类的引用传递给方法。
public interface IDamagable
{
void OnSimpleHit();
}
public interface IStabAble : IDamagable
{
void OnKnifeStab();
}
public interface ISlapAble : IDamagable
{
void OnSlap();
}
public abstract class Creature<T> where T : IDamagable
{
public abstract void Init(T damageListener);
}
public abstract class Human : Creature<ISlapAble>
{
}
public abstract class Spider : Creature<IStabAble>
{
}
public class MainClass
{
public void Test()
{
List<Spider> spiderList = new List<Spider>();
List<Human> humanList = new List<Human>();
PrintList<IDamagable>(spiderList); // Argument `#1' cannot convert
//`System.Collections.Generic.List<newAd.B_A_A>' expression
//to type `System.Collections.Generic.List<newAd.A_A<newAd.I_B>>'
}
protected void PrintList<T>(List<Creature<T>> list)
{
}
}
如果 PrintList 采用 2 个通用参数,这不会引发错误
protected void PrintList<T,U>(List<T> list) where T : Creature<U> where U : IDamagable
{
}
但是我不想再次传递 U,因为 T 已经用 U 作为类型参数构造了,例如 Spider 已经定义了 Creature 来获取 IStabAble 的类型参数。
所以基本上,我一直坚持如何编写方法,以便以最少的泛型参数同时满足 Spider 和 Human 的需求。
谢谢
【问题讨论】:
-
您应该考虑将您的类重命名为易于理解的名称,从而使您的类层次结构中的关系易于遵循。如果仅仅理解您的代码肯定会让人头疼,那么您将不会得到太多帮助。
-
尝试将
PrintList方法的签名改为void PrintList<T>(IEnumerable<A_A<T>> list) where T : I_A -
重命名了类和接口等 @YacoubMassad 我不明白将列表更改为 IEnumerable 有何改变
-
能否将文本中的所有内容重命名为?同样在注释代码中
-
@Farhan,与
List<T>不同,IEnumerable<T>中的泛型类型参数是covariant。
标签: c# generics inheritance parameter-passing