C# 速记:变量声明的类型后面跟着?的意思

  笔者近期在写.Net项目的时候,偶遇了很多比较有趣的C#小知识点(小标记符或者是优雅代码的书写方式),今天摘记一个有趣的变量声明方式:int? x=null;

  int? x表示的是声明了一个可以为null的int类型的变量,为什么需要这么做?因为int 属于值类型变量,理论上是不能为null的,但是我们通过这种方式就可以允许x为null了。

  x为null能做些什么?首先,你可以进行这样的判断了:

if(x==null){}
if(x!=null){}

  判断一个方法调用的值是否拿到了?或者是一个标志变化的变量是否变化了?等等。并且,还可以通过这样的变量进行如下的调用:

using System;

class NullableExample
{
  static void Main()
  {
      int? num = null;

      // Is the HasValue property true?
      if (num.HasValue)
      {
          Console.WriteLine("num = " + num.Value);
      }
      else
      {
          Console.WriteLine("num = Null");
      }

      // y is set to zero
      int y = num.GetValueOrDefault();

      // num.Value throws an InvalidOperationException if num.HasValue is false
      try
      {
          y = num.Value;
      }
      catch (InvalidOperationException e)
      {
         Console.WriteLine(e.Message);
      }
   }
}

  以及判断它是否有值:

int? x = 10;
if (x.HasValue)
{
    System.Console.WriteLine(x.Value);
}
else
{
    System.Console.WriteLine("Undefined");
}

综上,这种命名方式其实意义在于:我们如果采用的是值变量进行我们的方法调用成功与否的标识的时候,可能会遇到尽管调用失败,但是仍然不会出现我们预期的失败提示(因为值变量是有默认值的)。

最后,上官方文档传送门:Nullable Types (C# Programming Guide)

PS:这种值变量也支持装包和拆包(装\拆包定义可以百度下),给一段官方的示例代码:

The behavior of nullable types when boxed provides two advantages:

  • Nullable objects and their boxed counterpart can be tested for null:
bool? b = null;  

object boxedB = b;
if (b == null)
{
// True.
}
if (boxedB == null)
{
// Also true.
}


* Boxed nullable types fully support the functionality of the underlying type:

double? d = 44.4;
object iBoxed = d;
// Access IConvertible interface implemented by double.
IConvertible ic = (IConvertible)iBoxed;
int i = ic.ToInt32(null);
string str = ic.ToString();

猜你喜欢

转载自my.oschina.net/u/3744313/blog/1796293