简体   繁体   中英

Covariant use of generic Lazy class in C#

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);

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);

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM