gpt4 book ai didi

c# - 只允许将特定对象类型传递到基于派生类类型的方法中

转载 作者:行者123 更新时间:2023-12-03 22:18:36 24 4
gpt4 key购买 nike

我有一个基类,它有一个方法调用 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
{

}

我想知道,是否可以根据派生的 Bar 类类型只允许添加特定类型的 Fruit 类?

例如:

  • AppleBar 将只允许添加类型 Apple
  • BananaBar 将只允许添加类型 Banana

我知道我可以覆盖 AddFruit 方法,但我希望处理保留在基类中,并希望避免在覆盖的方法中调用 base.AddFruitBananaBarAppleBar 派生类关联的方法。

我还希望避免使用 GetType() 检查 Fruit 的类型。

理想情况下我想要如下内容:

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>
{
//...
}

更新

参见 this answer有关为什么不能添加 AppleBar 的解释到 List<Foo<Fruit>>

关于c# - 只允许将特定对象类型传递到基于派生类类型的方法中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24213185/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com