本文介绍了C#中通用Lazy类的协变使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假定适用:

public class Cat : Animal { }

并假设我有一个方法:

public void Feed(Animal animal) { ... }

我可以这样称呼:

var animal = new Cat();
Feed(animal);

Feed 时如何使此工作正常重构为仅支持 Lazy< Animal> 作为参数?我想以某种方式传递我的 var lazyAnimal = new Lazy< Cat>();

How can I get this working when Feed is refactored to only support Lazy<Animal> as parameter? I'd like to pass in my var lazyAnimal = new Lazy<Cat>(); somehow.

这显然不起作用:

var lazyAnimal = new Lazy<Cat>();
Feed(lazyAnimal);


推荐答案

好吧,您将无法使用它完全是这样。可能最简单的重构是让它接受 Func< Animal> 而不是 Lazy 。然后,您可以传入一个lambda来获取 Lazy 的值。 Func 就其返回类型而言是协变的。

Well, you won't be able to use it exactly as is. Probably the simplest refactor would be to have it accept a Func<Animal> instead of a Lazy. Then you could pass in a lambda that fetches the value of a Lazy. Func is covariant with respect to it's return type.

这篇关于C#中通用Lazy类的协变使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-11 16:33