首頁  >  文章  >  後端開發  >  C# 中的 is 運算符

C# 中的 is 運算符

PHPz
PHPz轉載
2023-09-13 23:01:021002瀏覽

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

在上面的範例中,檢查函數呼叫語句的類型相容性。只要被呼叫的函數是在類型中聲明的。結果會是真的。在這種情況下,結果將是錯誤的。 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 運算子的用法。

以上是C# 中的 is 運算符的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:tutorialspoint.com。如有侵權,請聯絡admin@php.cn刪除