C# 中的 Is 運算子


Is 運算子也稱為型別相容性運算子,在 C# 結構中起著不可或缺的作用。讓我們嘗試理解這個運算子。

C# 的 Is 運算子檢查給定物件是否與另一個物件相容,如果相容則返回 true,否則返回 false。

語法

expression is obj

示例

Expression 是您想要檢查與之相容性的物件。表示式可以包含變數、文字和方法呼叫。Obj 是驗證表示式所針對的型別。這可以包括內建型別和使用者定義型別。

// The operation of the type compatibility operator is performed.
Console.Writeline("Happy Holidays" is string);
Console.Writeline(42 is string);

輸出

True
False

讓我們理解這個輸出。我們知道“Happy Holidays”是一個字串文字,42 是一個整數。“Happy Holidays”與字串資料型別進行檢查時,結果為 true,因為它相容。當 42 與字串進行檢查時,結果為 false,因為它不相容。

表示式

字面量表達式

字面量表達式由數字、字元序列(字串)、陣列等組成。

示例

// The operation of the type compatibility operator is performed.
Console.Writeline("Happy Holidays" is string);

輸出

TRUE

變量表達式

變量表達式將包含充當容器的物件,這些物件儲存值或引用。

示例

// an object is declared with string data type.
object str= "Happy Holidays";
// The operation of the type compatibility operator is performed.
Console.Writeline(str is string);

輸出

TRUE

函式呼叫表示式

函式呼叫表示式將在 is 運算子的左側具有函式呼叫。

示例

// A class declaration
class class_dec{}
// an object is declared.
object str= Method_in_the_class();
// The operation of the type compatibility operator is performed.
Console.Writeline(str is class_dec);

輸出

TRUE

在上面的示例中,檢查函式呼叫語句的型別相容性。只要呼叫的函式在型別中宣告,結果都將為 true。在本例中,結果將為 false。class_dec 是一個空類。

型別

內建型別

C# 中的預定義型別可以在 is 運算子的右側使用。它可以是整數、字元、浮點數和布林值。

示例

// an object is declared with numeric data type.
object num= 42;
// The operation of the type compatibility operator is performed.
Console.Writeline(num is int);

輸出

TRUE

使用者定義型別

is 運算子也可以檢查使用者定義的型別。它包括類、列舉等。

示例

// A class declaration
class class_dec{}
// an instance of the class is declared.
class_dec str= new class_dec();
// The operation of the type compatibility operator is performed.
Console.Writeline(str is class_dec);

輸出

TRUE

在上面的示例中,is 運算子將物件與使用者定義的資料型別進行比較。

注意 - is 運算子也可以與 NULL 一起使用。如果表示式不為 null,則運算子將始終返回 false 作為輸出。

使用者定義型別的範圍會影響輸出。is 運算子應始終在宣告型別的範圍內使用。

結論

在本文中,我們重點介紹了 C# 中的 is 運算子。我們分析了語法並瞭解了 is 運算子可以使用的各種情況。is 運算子的使用透過各種程式碼片段和示例進行了說明。

更新於:2023年4月25日

307 次檢視

開啟您的 職業生涯

透過完成課程獲得認證

開始學習
廣告