gpt4 book ai didi

C# - 即使在正确的通用约束之后,堆栈推送操作也不起作用

转载 作者:行者123 更新时间:2023-11-30 12:37:52 25 4
gpt4 key购买 nike

namespace ConsoleApp3
{
class Program
{
// Main method - entry point of program
static void Main(string[] args)
{
var animals = new Stack<Animal>();
ZooCleaner.Wash(animals);
}
}

//Simple classes declared and inherited.
public class Animal { }
public class Bear : Animal{ }
public class Camel : Animal { }

public class Stack<T> //Basic stack implementation
{
int position;
T[] data = new T[100];
public void Push(T obj) => data[position++] = obj;
public T Pop() => data[--position];
}

public class ZooCleaner
{
public static void Wash<T>(Stack<T> animals) where T:Animal
{
//Why I cannot do this? I have correctly stated that 'T' can
//be of type Animal or can derive Animal but this
//still causes compilation error!

animals.Push(new Animal()); //Error: Cannot convert from 'Animal' To Type T!!
animals.Push(new Bear()); //Error: Cannot convert from 'Bear' To Type T!!
}
}
}

问题:

在 Wash() 方法中,我已经正确地将通用参数“T”设为“Animal”类型或可以派生自“Animal”。那么为什么我不能执行推送操作来插入 Animal 或 Bear 的对象?

为什么 animals.Push(new Animal()); animals.Push(new Bear()); 导致编译错误?

最佳答案

这是正常的,也是意料之中的。如果你有 Stack<T> where T : Animal ,那么你必须想象 T可能类似于 Giraffe .唯一允许您插入 Stack<Giraffe> 的东西是 Giraffe Giraffe 的东西(一个 MasaiGiraffe ,一个 NubianGiraffe 等)。你不能推 BearAnimal : 必须是 Giraffe (或更好)。

T的情况下,这意味着你可以推送 T - 也许是 new T() (通过 T : new() 约束)。

如果你希望能够推送任何Animal : 不要使用 Stack<T> where T : Animal - 使用 Stack<Animal> .

关于C# - 即使在正确的通用约束之后,堆栈推送操作也不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57867272/

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