I would use Lazy<T>
in general:
- It's thread-safe (may not be an issue in this case, but would be in others)
- It makes it obvious what's going on just by the name
- It allows null to be a valid value
Note that you don't have to use a lambda expression for the delegate. For example, here's an approach which may be slightly cleaner:
public static class Brushes
{
private static readonly Lazy<LinearGradientBrush> _myBrush =
new Lazy<LinearGradientBrush>(CreateMyBrush);
private static LinearGradientBrush CreateMyBrush()
{
var linearGradientBrush = new LinearGradientBrush { ...};
linearGradientBrush.GradientStops.Add( ... );
linearGradientBrush.GradientStops.Add( ... );
return linearGradientBrush;
}
public static LinearGradientBrush MyBrush
{
get { return _myBrush.Value; }
}
}
This is particularly handy when the creation process gets complicated with loops etc. Note that by the looks of it, you could use a collection initializer for GradientStops
in your creation code.
Another option is not to do this lazily, of course... unless you have several such properties in your class and you only want to create the relevant objects on a one-by-one basis, you could rely on lazy class initialization for many situations.
As noted in DoubleDown's answer, there's no way of resetting this to force recomputation (unless you make the Lazy<T>
field not readonly) - but I've very rarely found that to be important.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…