Lazy<T> reinitialization method?
We have a homebrew type that we have been using since .NET 3.5 where I work that does the same thing as Lazy< T > class yet allows you to have the instance re-evaluate the Lazy Func. We would like to replace our class with the new .NET one but this Clear() or IsDirty mechanism doesn't exist.
Is there a way to reinitialize the Lazy< T > Func method without re开发者_开发知识库instantiating the class? If not, is there a way to implement it as an extension method or is just just a bad pattern to follow in the first place?
Because it is impossible to make it thread-safe. Classes that guarantee that the programmer will shoot his leg off without any way to fix the problem don't belong in a framework. You are free to shoot your own leg off.
What you want to do isn't Lazy initialization, it's something else. That's why it isn't on the Lazy<T> class. 
Because that would break the semantics of the type. If the state of the Lazy<T> becomes invalid over time you need to consider a different type.
If you really need to reset your Lazy<> object you need to have the mechanism to make new instance of Lazy<> type. You could build a wrapper that exposes the same properties as Lazy<> type plus Reset-method which simply recreates it. In simple terms it would be something like:
public class ResettableLazy<T>
{
    public T Value => this.Container.Value;
    public bool IsValueCreated => this.Container.IsValueCreated;
    public void Reset() { this.Container = new Lazy<T>(); }
    private Lazy<T> Container = new Lazy<T>();
}
The real question is should you do something like that, but if you really need to that might be enough for your needs.
 
         加载中,请稍侯......
 加载中,请稍侯......
      
精彩评论