联合继承,实现和泛型问题

时间:2015-07-10 10:22:29

标签: c# generics inheritance interface implementation

在下面的示例中,我想创建从PuppyBase基类继承的多种类型的Puppies,它们实现IPuppy通用接口。基类中的Bark方法,其他方法 - 在派生的CutePuppy类中。

我无法得到如何在这里创建另一只想要另一种饲料而且吠叫不同的小狗?

public interface IPuppy<TBark, TDesiredFood>
{
    void Bark(TBark sound);
    Task<TDesiredFood> Sleep();
    Task Eat(TDesiredFood food);
}

public abstract class PuppyBase:IPuppy<Yap,Sausage>
{
    public void Bark(Yap sound)
    {
        Console.WriteLine(sound.ToString());
    }

    public abstract Task<Sausage> Sleep();
    public abstract Task Eat(Sausage food);
}

class CutePuppy : PuppyBase
{
    public override Task<Sausage> Sleep()
    {
        // Implementation
        // ...
        throw new NotImplementedException();
    }

    public override Task Eat(Sausage food)
    {
        // Implementation
        // ...
        throw new NotImplementedException();
    }
}

1 个答案:

答案 0 :(得分:3)

为了能够在基类上指定泛型类型,您可以使它也是通用的

public abstract class PuppyBase<TBark, TDesiredFood> : IPuppy<TBark, TDesiredFood>
    where TBark : ISound
{
    public void Bark(TBark sound)
    {
        Console.WriteLine(sound.ToString());
    }

    public abstract Task<TDesiredFood> Sleep();
    public abstract Task Eat(TDesiredFood food);
}

public interface ISound
{
    string ToString();
}

对于CutePuppy这种方式你应该

class CutePuppy : PuppyBase<Yap,Sausage>

for NotSoNicePuppy

class NotSoNicePuppy: PuppyBase<Wow,Human>