zoukankan      html  css  js  c++  java
  • 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; }
    }
  • 相关阅读:
    51nod-1420-贪心
    51nod-1455-dp/缩小范围
    51nod-1574-排列转换
    简单的鼠标滚轮事件
    数组去重
    模仿jq里的选择器和color样式
    在页面里写个动态本地时间
    使用css中的flex布局弹性手风琴效果
    bootstrap中如何多次使用一个摸态框
    使用css让文字两端对齐
  • 原文地址:https://www.cnblogs.com/chucklu/p/13255358.html
Copyright © 2011-2022 走看看