我正在开发一个 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
。有人可以解释为什么会发生这种情况以及我该如何解决它吗?”
泛型的要点是不需要创建多个方法来返回类型
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
函数确定需要返回的类型,就可以依赖这些私有封装方法。