zoukankan      html  css  js  c++  java
  • 利用??运算符简化单件模式代码

     1using System;
     2using System.Collections.Generic;
     3using System.Text;
     4
     5namespace ConsoleApplication1
     6{
     7    class Program
     8    {
     9        static void Main(string[] args)
    10        {
    11            Test t = Test.Instance();
    12            Console.WriteLine(t.ToString());
    13            Test c = Test.Instance();
    14            Console.WriteLine(c.ToString());
    15            Console.ReadLine();
    16        }

    17    }

    18
    19    public class Test 
    20    {
    21        public static int x = 1;
    22        private static Test m_Instance;
    23
    24        private Test() 
    25        {
    26            x++;
    27        }

    28
    29        public static Test Instance() 
    30        {
    31            if (m_Instance == null)
    32            {
    33                m_Instance = new Test();
    34            }

    35            else 
    36            {
    37                return m_Instance;
    38            }

    39        }

    40       
    41        public override string ToString()
    42        {
    43            return x.ToString();
    44            
    45        }

    46    }

    47}

    48

    这是单件模式的基本代码,在这里重载了tostring()方法来查看TEST到底被实例化了多少次,在看了MSDN中关于??运算符的帮助后试着用如下方法来重写INSTANCE方法
       public static Test Instance()
            {
                m_Instance = m_Instance ?? new Test();
                return m_Instance;
            }
    同样可以达到单件模式的功能

    MSDN中关于??操作符的定义

    如果 ?? 运算符的左操作数非空,该运算符将返回左操作数,否则返回右操作数。

    可空类型可以包含值,或者可以是未定义的。?? 运算符定义当可空类型分配给非可空类型时返回的默认值。如果在将可空类型分配给非可空类型时不使用 ?? 运算符,将生成编译时错误。如果使用强制转换,并且当前未定义可空类型,将发生 InvalidOperationException 异常。

  • 相关阅读:
    js getAttribute()和setAttribute()方法
    FCKeditor上传图片显示叉叉的问题的解决方案
    数据导出
    插入多种格式的网页播放器
    注册机...郁闷..
    AJAX效果
    2003下使用JMAIL问题解决办法
    ASP无组件上传带进度条
    MSSQL查询题解
    在线转flv+flash在线录制视频
  • 原文地址:https://www.cnblogs.com/forrestsun/p/548830.html
Copyright © 2011-2022 走看看