Covariant use of generic Lazy class in C#

≯℡__Kan透↙ 提交于 2019-12-10 16:17:04

问题


Assuming that this applies:

public class Cat : Animal { }

and assuming that I have a method:

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

And I can call it this way:

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

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.

This obviously doesnt work:

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

回答1:


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.




回答2:


You can't, basically - not directly, anyway. Lazy<T> is a class, so doesn't suppose generic variance.

You could create your own ILazy<out T> interface, implement it using Lazy<T>, and then make Feed take ILazy<Animal> instead. The implementation would be trivial.

Alternatively, you could make Feed generic:

public void Feed<T>(Lazy<T> animal) where T : Animal

Or Servy's suggestion of taking Func<Animal> would work too, and you could call it using a lambda expression for the Lazy<T>:

Feed(() => lazyAnimal.Value);


来源:https://stackoverflow.com/questions/21117619/covariant-use-of-generic-lazy-class-in-c-sharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!