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

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?

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

B) Is there any difference to this?

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

 

Properties and fields behave entirely differently, even though they might appear similar from a coding point of view.

A property is actually just a shortcut for a pair of get/set methods, and like any method, the body will be executed each time you call it..

 

回答:

In your first example, LoadSearchList() will be called each time the property is accessed.

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).

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):

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

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

 

作者:Chuck Lu    GitHub    
posted @   ChuckLu  阅读(120)  评论(0编辑  收藏  举报
编辑推荐:
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
历史上的今天:
2018-07-06 What does jQuery.fn mean?
2018-07-06 Bootstrap4 网格系统
2017-07-06 out
2017-07-06 TortoiseSvn安装的时候,将svn的命令行工具单独隔离出来
2015-07-06 Binary to Text (ASCII) Conversion
2015-07-06 Pizza pieces
点击右上角即可分享
微信分享提示