问题
In a design of the public interface of a library, is it legitimate to return an instance of Lazy<T> in a property, if I want lazy initialization? Or is it better to always hide the usage of Lazy<T>
by means of encapsulation or other techniques?
回答1:
For the following I'm assumim you mean a Lazy Property.
It depends on the purpose of your interface.
Is it an important detail that the consumer knows that it is lazy ? Or is it just a technical detail which should not change the behavior for the consumer.
It you only have a short delay which must not be handled by the consumer then i would tend to haide the Lazy and only expose T directly.
If the consumer should be aware and may adapt this behavior then i would expose the lazy .
But thiking on this I would in most cases rather expose a method which indicates that the code may have side effects or may take a while.
回答2:
I don't see any reason to directly expose Lazy<T> in the signature. In my use cases, the laziness is an implementation detail.
Don't use this in a property if initialization is long running. In such cases, rather provide a method, considering returning Task<T>.
来源:https://stackoverflow.com/questions/31043096/should-i-avoid-exposing-the-lazyt-class-in-public-api