System.Lazy 延遲初始化

  • 1803
  • 0
  • C#
  • 2016-06-29

摘要:System.Lazy 延遲初始化

MSDN的解釋
System.Lazy<T> 類別使得將物件延遲初始化和延遲執行個體化的工作變得簡單。藉由將物件延遲初始化,您不必再事先建立可能永遠都用不到的物件,而且可以將物件延到初次存取該物件時再初始化。
 
運用Design Pattern中的 Singleton Pattern,可以更了解效果
public class Singleton
    {
        private static Singleton test;
        private string str = " Testing";
        private Singleton(int data)
        {
            str = " Start " + str + " " + data;
        }

        public static Singleton getInstance(int data)
        {
            if (test == null)
                test = new Singleton(data);
            return test;
        }

        public static Singleton getObject()
        {
            return test;
        }

        public string getMsg()
        {
            return str;
        }
    }
前端程式
public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        Lazy lazy = null;
        Singleton tObject = null;
        private void button1_Click(object sender, EventArgs e)
        {
            string sRes = "";
            this.lazy = new Lazy(() => Singleton.getInstance(1));

            //取得Singleton
            tObject = Singleton.getObject();
            if (tObject == null)
            {
                sRes += "Singleton 尚未初始化" + Environment.NewLine;
            }

            //Singleton實體化
            if (this.lazy.Value != null)
            {
                sRes += "Lazy.Value 呼叫" + Environment.NewLine;
            }

            //重新取得Singleton
            tObject = Singleton.getObject();
            if (tObject != null)
            {
                sRes += "Test 已經初始化了" + Environment.NewLine;
            }
            else
            {
                sRes += "Test 尚未初始化" + Environment.NewLine;
            }

            sRes += tObject.getMsg();
            MessageBox.Show(sRes);
        }
    }
 
前端畫面
 
 
執行結果
 
流程說明