我发现这篇文章是关于Lazy:C#4.0中的懒惰 - 懒惰
使用Lazy对象获得最佳性能的最佳实践是什么?有人能指出我在实际应用中的实际用途吗?换句话说,我什么时候应该使用它?
我需要一个可以从我想要的地方分配的字段,但是应该可以只分配一次(因此应该忽略后续的分配).我怎样才能做到这一点?
我刚刚了解了VB.NET中静态局部变量的用法,并想知道它在延迟加载属性中的潜在用途.
请考虑以下示例代码.
Public Class Foo
Implements IFoo
End Class
Public Interface IFoo
End Interface
Public Class Bar
Private _fooImplementation As IFoo
Public ReadOnly Property FooImplementation As IFoo
Get
If _fooImplementation Is Nothing Then _fooImplementation = New Foo
Return _fooImplementation
End Get
End Property
End Class
Run Code Online (Sandbox Code Playgroud)
这将是一种通常的,简化的延迟加载属性.您甚至可能希望使用通用的Lazy Class来获取(据我所知)相同的行为.
现在,让我们在使用静态变量时查看属性.
Public Class Bar
Public ReadOnly Property FooImplementation As IFoo
Get
Static _fooImplementation as IFoo = New Foo
Return _fooImplementation
End Get
End Property
End Class
Run Code Online (Sandbox Code Playgroud)
据我所知,这比通常的实现有一些优点,主要是你无法访问属性之外的变量,以及不必使用额外的变量.
我的问题是:其中哪一种是"正确"的方式?我知道静态变量有额外的开销,但是在我个人看来,创建可能被滥用的不清除代码是否足够糟糕?与"传统"方法相比,您失去了多少性能?与大型工厂相比,小班级如何重要?
提前致谢.