技術(shù)頻道導(dǎo)航
HTML/CSS
.NET技術(shù)
IIS技術(shù)
PHP技術(shù)
Js/JQuery
Photoshop
Fireworks
服務(wù)器技術(shù)
操作系統(tǒng)
網(wǎng)站運營

贊助商

分類目錄

贊助商

最新文章

搜索

[C#技巧]C#進行空(null)檢查的正確方法:用is代替==

作者:admin    時間:2023-5-6 12:51:2    瀏覽:

我們在代碼中經(jīng)常執(zhí)行 null 檢查,以防止NullReferenceException,我們最常見的方法是:

var product = GetProduct();
if (product == null)
{
    // Do something if the object is null.
}

你知道這種方法有什么問題嗎?==運算符可以被覆蓋,并且不能嚴格保證將對象與null進行比較,會產(chǎn)生我們期望的結(jié)果。

C# 版本 7

C# 版本 7 中引入了一個新的運算符,即is運算符。

以下是我們?nèi)绾问褂?code>is運算符執(zhí)行空檢查:

var product = GetProduct();
if (product is null)
{
    // Do something if the object is null.
}

is運算符將始終評估指定的對象實例是否為null。它也是一種更簡潔的空檢查編寫方式,因為它讀起來像一個句子。

C# 版本 9

從 C# 9 開始,你可以使用否定模式進行空檢查:

var product = GetProduct();
if (product is not null)
{
    // Do something if the object is not null.
}

C# 版本 11

從 C# 11 開始,你可以使用列表模式來匹配列表或數(shù)組的元素。以下代碼檢查數(shù)組中預(yù)期位置的整數(shù)值:

int[] empty = { };
int[] one = { 1 };
int[] odd = { 1, 3, 5 };
int[] even = { 2, 4, 6 };
int[] fib = { 1, 1, 2, 3, 5 };

Console.WriteLine(odd is [1, _, 2, ..]);   // false
Console.WriteLine(fib is [1, _, 2, ..]);   // true
Console.WriteLine(fib is [_, 1, 2, 3, ..]);     // true
Console.WriteLine(fib is [.., 1, 2, 3, _ ]);     // true
Console.WriteLine(even is [2, _, 6]);     // true
Console.WriteLine(even is [2, .., 6]);    // true
Console.WriteLine(odd is [.., 3, 5]); // true
Console.WriteLine(even is [.., 3, 5]); // false
Console.WriteLine(fib is [.., 3, 5]); // true

總結(jié)

本文介紹了C#進行空(null)檢查的正確方法:用is代替==,不過在使用之前,要先考慮自己使用的C#版本,因為is運算符只能在C# 7后使用。

相關(guān)文章

x
  • 站長推薦
/* 左側(cè)顯示文章內(nèi)容目錄 */