简体   繁体   English

初始化静态字段与返回静态属性中的值获取?

[英]Initializing a static field vs. returning a value in static property get?

A) In the following code, will the method DataTools.LoadSearchList() only be called once, or every time the property is being accessed? A) 在下面的代码中,方法DataTools.LoadSearchList()只调用一次,还是每次访问属性时调用?

public static IEnumerable<string> SearchWordList
{
    get
    {
        return DataTools.LoadSearchList();
    }
}

B) Is there any difference to this? B) 这有什么区别吗?

public static IEnumerable<string> SearchWordList = DataTools.LoadSearchList();

In your first example, LoadSearchList() will be called each time the property is accessed.在您的第一个示例中,每次访问该属性时都会调用 LoadSearchList()。

In the second, LoadSearchList() will only be called once (but it will be called whether you use it or not since it is now a field rather than a property).在第二个中, LoadSearchList() 只会被调用一次(但无论您是否使用它都会被调用,因为它现在是一个字段而不是一个属性)。

A better option might be:更好的选择可能是:

private static IEnumerable<string> _searchWordList;

public static IEnumerable<string> SearchWordList
{
    get 
    { 
        return _searchWordList ?? 
            ( _searchWordList = DataTools.LoadSearchList()); 
    }
}

Or if you're using .NET 4.0 and want something thread-safe you can use Lazy<T> , as Jon Skeet mentioned (I think the syntax should be correct, but don't hold me to it):或者,如果您使用 .NET 4.0 并且想要线程安全的东西,您可以使用Lazy<T> ,正如 Jon Skeet 所提到的(我认为语法应该是正确的,但不要强迫我):

private static Lazy<IEnumerable<string>> _searchWordList =
    new Lazy<IEnumerable<string>>(() => DataTools.LoadSearchList());

public static IEnumerable<string> SearchWordList
{
    get { return _searchWordList.Value; }
}

In the first case the method will be called every time the property is accessed.在第一种情况下,每次访问属性时都会调用该方法。 When it's set as a field, it will be run exactly once - when the type it initialized - whether or not it's ever accessed.当它被设置为一个字段时,它将只运行一次 - 当它初始化类型时 - 无论它是否曾经被访问过。

If you want a lazily-initialized value, I'd recommend Lazy<T> from .NET 4.如果你想要一个延迟初始化的值,我会推荐 .NET 4 中的Lazy<T>

Yes, the property will call DataTools.LoadSearchList() every time access.是的,每次访问该属性都会调用 DataTools.LoadSearchList()。 The static field will only call the method once.静态字段只会调用该方法一次。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM