gpt4 book ai didi

c# - 泛型和类继承的混淆

转载 作者:行者123 更新时间:2023-12-02 09:41:30 24 4
gpt4 key购买 nike

我有以下代码块作为我遇到的问题的简化示例。但我收到一条错误消息,声称我无法将一种类型转换为另一种类型。我用LINQPad来测试它。

void Main()
{
LivingThing<Appendage> mysteryAnimal = new Cat();
}

public class Appendage { }
public class Paw : Appendage { }

public class LivingThing<TExtremity> where TExtremity : Appendage { }
public class Animal<TExtremity> : LivingThing<TExtremity> where TExtremity : Appendage { }
public class Cat : Animal<Paw> { }

为什么我无法转换CatLivingThing<Appendage>当我知道 Cat 的定义正在使用 LivingThing 的子类时和Appendage

最佳答案

通过向您的某个类添加方法,可以更容易地了解为什么您尝试做的事情在不进行一些修改的情况下无法工作:

public class LivingThing<TExtremity> where TExtremity : Appendage {
private TExtremity extremity;
public void SetExtremity(TExtremity e) {
extremity = e;
}
}

现在让我们想象一下 C# 可以让您完成作业。然后它应该让你这样做:

public class Hand : Appendage { }
...
// Let's pretend this works
LivingThing<Appendage> cat = new Cat();
// Now that C# let us do the assignment above, it must allow this too,
// because Cat is a LivingThing and Hand is an Appendage:
cat.SetExtremity(new Hand());

哎呀,我们有一只有手的猫! C# 不应该让我们这样做。

如果 LivingThing 的话,做你想做的事情是可能的有返回 TExtremity 的方法, 尽管。 C# 提供了定义继承层次结构的方法,使您可以按照您尝试的方式灵活地进行分配。这是您修改后的有效代码:

void Main()
{
ILivingThing<Appendage> mysteryAnimal = new Cat();
}

public class Appendage { }
public class Paw : Appendage { }

public interface ILivingThing<out TExtremity> where TExtremity : Appendage { }
// You have a choice of keeping Animal a class. If you do, the assignment
// Animal<Appendage> mysteryAnimal = new Cat()
// would be prohibited.
public interface IAnimal<TExtremity> : ILivingThing<out TExtremity> where TExtremity : Appendage { }
public class Cat : Animal<Paw> { }

有一个问题: ILivingThing<TExtremity> 都不是也不IAnimal<TExtremity>允许具有 TExtremity 类型的可设置属性或采用 TExtremity 的方法作为一个论点。

关于c# - 泛型和类继承的混淆,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28992314/

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