在VB.NET的延迟加载属性中使用静态局部变量 [英] Use of static local variables in lazy loading property in VB.NET

查看:110
本文介绍了在VB.NET的延迟加载属性中使用静态局部变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我最近才了解VB.NET中静态局部变量的用法,并想知道它在延迟加载属性中的潜在用途.

I just recently learned about the uses of static local variables in VB.NET and wondered about it's potential use in lazy loading properties.

请考虑以下示例代码.

Consider the following example code.

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

这将是通常的,简化的延迟加载属性.您甚至可能希望使用通用的惰性类来获得(据我所知)相同的行为.

This would be a usual, simplified lazy-loading property. You may even want to use the generic Lazy Class to get (as far as i know) the same behaviour.

现在,让我们在使用静态变量的同时查看该属性.

Now, let's look at the property while using a static variable.

Public Class Bar

  Public ReadOnly Property FooImplementation As IFoo
    Get
      Static _fooImplementation as IFoo = New Foo
      Return _fooImplementation
    End Get
  End Property
End Class

据我所知,与常规实现相比,它具有一些优点,主要是您无法访问属性外部的变量,以及不必使用其他变量.

As far as i can see, this has a few advantages over the usual implementation, primary your inability to access the variable outside of the property, as well as not having to use an additional variable.

我对您的问题是:正确"的方法是哪一种?我知道静态变量会带来额外的开销,但是以我个人的观点来说,创建不清晰的代码会更容易被滥用吗?与传统"方法相比,您损失了多少性能?与大工厂相比,小班制对他们有什么影响?

My question to you is: Which of those is the "right" way to do it? I know that static variables have additional overhead, but is it bad enough to create, in my personal opinion, unclearer code that can be misused easier? How much performance do you lose compared to the "traditional" method? How does it matter for small classes compared to huge factories?

谢谢.

推荐答案

Static 关键字具有相当大的开销,编译器会生成大量的IL来实现它.第一个代码片段不执行的操作是确保线程不会引起问题.如果这不是一个问题,那么您的第一段代码要便宜很多.不仅因为它的IL少得多,而且因为它会被内联.带有Static的吸气剂永远不会内联,因为它包含Try/Finally代码.

The Static keyword has rather a lot of overhead, the compiler generates a big chunk of IL to implement it. What it does do that your 1st snippet doesn't do is ensure that threading doesn't cause problems. If that is not a concern then your 1st snippet is a lot cheaper. Not just because it has a lot less IL but also because it will be inlined. A getter with Static will never be inlined since it contains Try/Finally code.

如果您以.NET 4为目标,那么您绝对应该看看Lazy(T)类.

If you are targeting .NET 4 then you definitely should take a look at the Lazy(Of T) class.

这篇关于在VB.NET的延迟加载属性中使用静态局部变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆