避免传递扩展泛型类

时间:2016-05-18 10:17:47

标签: c# generics inheritance parameter-passing

我有一个抽象类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的需求。
感谢

1 个答案:

答案 0 :(得分:2)

我假设PrintList只需要对列表进行只读向前访问。

解决方案是让PrintList方法接受IEnumerable<Creature<T>>,如下所示:

void PrintList<T>(IEnumerable<Creature<T>> list) where T: IDamagable
{
    //...
}

并称之为:

PrintList(spiderList);

由于T中的通用类型参数IEnumerable<T>covariant,因此可以使用。

在您的特殊情况下,因为您使用的是.NET 2.0(不支持协变类型参数),所以此解决方案不起作用。这是一个解决方法:

创建一个Cast方法,可以在具有不同项类型的枚举之间进行转换(在.NET 3.5中,我们已经有这样的方法作为扩展方法):

public static IEnumerable<U> Cast<T, U>(IEnumerable<T> source) where T : U
{
    foreach (var item in source)
    {
        yield return item;
    }
}

并像这样使用它:

PrintList(Cast<Spider, Creature<IStabAble>>(spiderList));