gpt4 book ai didi

c# - 在 C# 中使用 Func 的多态性

转载 作者:行者123 更新时间:2023-11-30 17:40:20 25 4
gpt4 key购买 nike

<分区>

上周我遇到了一个有趣的问题,我不确定我是否真正理解了 following code 的多态性。 .我根据自己编写的一些代码创建了这个示例。

基本设置

  • 我有一个知道如何训练动物的“训练师”类(class)。
  • 我将其用作基类并创建了一个子类“DogTrainer”,它只知道如何训练狗。
  • 我使用父类(super class)作为返回类型创建了一个函数指针。
  • 然后我调用该函数获取子类“DogTrainer”的新实例。
  • 然后我调用从函数指针返回的实例的“Train”方法。
  • “Train”方法按预期调用“Trainer”-“Train”方法而不是“DogTrainer”-“Train”方法

这是代码

// Does not work as expected
// Calls the Trainer Train not the DogTrainer Train
var getTrainer = new Func<Trainer>(() => new DogTrainer(new Dog()));
var funcTrainer = getTrainer();
Console.WriteLine(funcTrainer.Train());

现在,如果我使用接口(interface)作为返回类型,它会按预期“IF”工作,我将接口(interface)直接标记在“DogTrainer”子类上

// Works as expected 
var getITrainer = new Func<ITrainer>(() => new DogTrainer(new Dog()));
var funcITrainer = getITrainer();
Console.WriteLine(funcITrainer.Train());

如果我在子类上没有接口(interface),它就不会按预期工作。 See Example

// Does not work as expected 
// Calls the Trainer Train not the Dog Trainer Train
var getITrainerWithNoInterface = new Func<ITrainer>(() => new DogTrainerWithNoInterface(new Dog()));
var funcITrainerWithNoInterface = getITrainerWithNoInterface();
Console.WriteLine(funcITrainerWithNoInterface.Train());

如果有人能让我知道我在这里缺少什么,这种行为不是我所期望的。当我在我的代码中发现这个错误时,我能够解决它,我在这里寻找的是发生这种情况的“原因”。

这是DogTrainerWithNoInterface,它可能是拼图的主要部分(Trainer:ITrainer)

public class DogTrainerWithNoInterface : Trainer
{
public DogTrainerWithNoInterface(IAnimal animal)
: base(animal)
{ }

public new string Train()
{
return $"Speak Ubu, Speak : {Animal.Speak()}";
}
}

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