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 异常。

  • 相关阅读:
    ipmitool常用命令
    linux系统/var/log目录下的信息详解
    查看vnc server的日志
    Hp服务器 iLO3 使用方法
    phalcon builder 用法
    cobbler pxe-menu
    几种session存储方式比较
    parse arguments in bash
    No breeds found in the signature, a signature update is recommended
    Mybatis-plus使用分页进行分页查询
  • 原文地址:https://www.cnblogs.com/forrestsun/p/548830.html
Copyright © 2011-2022 走看看