Pregunta

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);
¿Fue útil?

Solución 2

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.

Otros consejos

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);
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top