如何在 C# 中將字串解析為可空整數?


C# 提供了特殊資料型別(可空型別),可以為它分配正常範圍的值以及空值。

C# 2.0 引入了可空型別,允許為值型別變數分配 null。可以使用 Nullable 宣告可空型別,其中 T 為型別。

  • 可空型別只能用於值型別。

  • 如果值為 null,Value 屬性將丟擲 InvalidOperationException;否則它將返回該值。

  • HasValue 屬性在變數包含值時返回 true,或在為空時返回 false。

  • 僅可對可空型別使用 == 和 != 運算子。對於其他比較,使用 Nullable 靜態類。

  • 不允許巢狀可空型別。Nullable<Nullable<int>> i; 將產生編譯時錯誤。

示例 1

static class Program{
   static void Main(string[] args){
      string s = "123";
      System.Console.WriteLine(s.ToNullableInt());
      Console.ReadLine();
   }
   static int? ToNullableInt(this string s){
      int i;
      if (int.TryParse(s, out i)) return i;
      return null;
   }
}

輸出

123

將 Null 傳遞到擴充套件方法時不會列印任何值

static class Program{
   static void Main(string[] args){
      string s = null;
      System.Console.WriteLine(s.ToNullableInt());
      Console.ReadLine();
   }
   static int? ToNullableInt(this string s){
      int i;
      if (int.TryParse(s, out i)) return i;
      return null;
   }
}

輸出

更新於:07-11-2020

5K+ 瀏覽

開啟您的職業生涯

完成本課程取得認證

開始
廣告
© . All rights reserved.