为什么我不能在 C# 中使用返回具有不同类型参数的泛型类的函数列表

问题描述 投票:0回答:1

我正在开发一个 C# 项目,其中有一个接口

IAnimal
和两个实现该接口的类
Dog
Cat
。我还有一个泛型类
Zoo<T>
,其中
T
是实现
IAnimal
的类型。

相关代码如下:

public interface IAnimal { /* ... */ }

public class Dog : IAnimal { /* ... */ }

public class Cat : IAnimal { /* ... */ }

public class Zoo<T> where T : IAnimal { /* ... */ }

我正在尝试创建两个函数

CreateZooOfDog
CreateZooOfCat
分别返回
Zoo<Dog>
Zoo<Cat>
。然后我想将这些函数添加到列表中并循环调用它们。这是我尝试过的:

public Zoo<Dog> CreateZooOfDog() { /* ... */ }

public Zoo<Cat> CreateZooOfCat() { /* ... */ }

var zooes = new List<Func<Zoo<IAnimal>>>();

Func<Zoo<Dog>> zooOfDog = () => program.CreateZooOfDog();
Func<Zoo<Cat>> zooOfCat = () => program.CreateZooOfCat();

zooes.Add(zooOfDog);
zooes.Add(zooOfCat );

但是,我在

CreateZooOfDog
CreateZooOfCat
上遇到编译时错误。

我不明白为什么会发生这种情况,因为

Dog
Cat
都实现了
IAnimal
。有人可以解释为什么会发生这种情况以及我该如何解决它吗?”

c# list function generics type-conversion
1个回答
0
投票

泛型的要点是不需要创建多个方法来返回类型

T
。拥有一个接受
IAnimal
但仅返回
Dog
类型的特定方法,然后再返回一个
Cat
类型就违背了使用泛型的目的。

使用一个接受类型的方法会更有意义

IAnimal
确定需要返回的类型并返回它。

public interface IAnimal {  }

public class Dog : IAnimal {  }

public class Cat : IAnimal {  }

public class Zoo<T> where T : IAnimal {  }
public Zoo<T> CreateZoo<T>(T animal)
{
    //Determine type T that needs to be returned 
    if (animal is Cat)
        //
    if (animal is Dog)
        //
}

然后只需转换为需要的类型即可。

Dog dog = (Dog)zooObj.CreateZoo(new Dog());
Cat cat = (Cat)zooObj.CreateZoo(new Cat());

这将更好地使用泛型并减少有效执行相同操作的多个函数。特定于

Dog
或特定于
Cat
的其他函数可以是私有的,一旦
CreateZoo
函数确定需要返回的类型,就可以依赖这些私有封装方法。

© www.soinside.com 2019 - 2024. All rights reserved.