在下面的示例中,我想创建从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();
}
}
答案 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>