我有一个基类,该基类具有方法调用AddFruit
,该方法采用Fruit
类型的类并以一般方式对其进行处理。
public abstract class Foo
{
protected List<ProcessedFruit> processedFruit = new List<ProcessedFruit>();
public void AddFruit(Fruit o)
{
// Process fruit
processedFruit.Add(o);
}
public void Update()
{
// Do base class specific stuff here
OnUpdate();
}
protected abstract void OnUpdate();
}
public class AppleBar : Foo
{
public AppleBar()
:base(){}
protected override void OnUpdate() { }
}
public class BananaBar : Foo
{
public BananaBar()
:base(){}
protected override void OnUpdate() { }
}
从
Foo
派生的任何类都将以非通用方式进行更新,并且将以不同的方式使用ProcessedFruit
列表。可以在实例化
Fruit
类之后的任何时间添加和处理Bar
。 public abstract class Fruit
{
}
public class Banana : Fruit
{
}
public class Apple : Fruit
{
}
我想知道,是否可能仅允许基于派生的
Fruit
类类型添加Bar
类的特定类型?例如:
AppleBar
仅允许添加Apple
类型BananaBar
仅允许添加Banana
类型我知道可以覆盖
AddFruit
方法,但是我希望处理保留在基类中,并且希望避免在与base.AddFruit
和BananaBar
派生类相关联的重写方法中调用AppleBar
。我也希望避免使用
Fruit
检查GetType()
的类型。理想情况下,我想要以下内容:
var o = new AppleBar()
// This has to be an Apple and intellisense can recognise this
o.AddFruit(...);
这可能吗?
编辑:
我在使用泛型时遇到以下问题:
List<Foo<Fruit>> commands = new List<Foo<Fruit>>(10);
commands.Add(new AppleBar()); // Can't be added
commands.Add(new BananaBar()); // Can't be added
最佳答案
最简单的方法是在基类上使用通用类型参数,然后由继承类使用特定类型填充该参数:
public abstract class Foo<T> where T : Fruit
{
protected List<ProcessedFruit> processedFruit = new List<ProcessedFruit>();
public void AddFruit(T o)
{
// Process fruit
processedFruit.Add(o);
}
public void Update()
{
// Do base class specific stuff here
OnUpdate();
}
protected abstract void OnUpdate();
}
public class AppleBar : Foo<Apple>
{
//...
}
更新资料
有关为什么无法将
AppleBar
添加到List<Foo<Fruit>>
的说明,请参见this answer关于c# - 仅允许将特定的对象类型传递到基于派生类类型的方法中,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/24213185/