介面之間的轉換

2022-09-28 23:45:21 字數 2077 閱讀 3644

**

目錄在 c# 中,在介面之間進行強制轉換的最佳方法是使用 as 運算子。 使用 as 運算子是比直接強制轉換更好的編碼策略,因為它在轉換失敗時產生 null 而不是引發異常。

以下**示例中,第一行是直接轉換。 如果您確定所討論的物件實現了這兩個介面,這是一種可接受的做法。 如果物件未實現您嘗試獲取控制代碼的介面,.net 將引發異常。 使用更安全的方式,是 as 運算子,如果物件無法返回【對所需介面的引用】,則返回 null。

[c#]

igeometry geometry=(igeometry)point; // straight cast.

igeometry geometry=point as igeometry; // as operator.

以下**示例顯示了,如何在顯式強制轉換後,管理返回空介面控制代碼的可能性:

[c#]

ipoint point=new pointclass();

igeometry geometry=point as igeometry;

if (geometry != null)

或者,您可以在執行直接轉換之前,使用 is 關鍵字,測試物件在執行時是否實現了某個介面。 請參見以下**示例:

[c#]

ipoint point=new pointclass();

if (point is igeometry)

以下是型別轉換的2種方式:

請參見以下**示例:

[vb.net]

'implicit cast.

geometry=point

'explicit cast.

geometry=ctype(point, igeometry)

geometry=directcast(point, igeometry)

geometry=trycast(point, igeometry)

在介面之間進行轉換時,使用隱式轉換是可以接受的,因為在數字型別之間進行轉換時,不會丟失資料。 但是,當強制轉換失敗時,會引發異常 (system.invalidcastexception)。 為避免處理不必要的異常,最好事先測試物件是否實現了這兩個介面。 您可以使用 typeof 關鍵字對此進行測試,該關鍵字是乙個【比較子句】,用於測試物件是否派生自或實現特定型別、介面。

以下**示例,執行了從 ipoint 到 igeometry 的隱式轉換,僅當在執行時才確定 point 類實現了 igeometry 時:

[vb.net]

dim point as new pointclass

dim geometry as igeometry

if typeof point is igeometry then

geometry=point

end if

如果您更喜歡使用 option strict on 語句來限制隱式轉換,請使用 ctype 或 directcast 函式進行顯式強制轉換。 以下**示例,對上乙個**示例進行了顯式轉換:

[vb.net]

dim point as new pointclass

dim geometry as igeometry

if typeof point is igeometry then

geometry=ctype(point, igeometry)

end if

或者,您可以跳過 typeof 比較,並使用 trycast,它在轉換失敗時,返回 nothing。 請參見以下**示例:

[vb.net]

dim point as new pointclass

dim geometry as igeometry=trycast(point, igeometry)

if geometry isnot nothing then

console.writeline(geometry.geometrytype.tostring())

end if

2 07 Go之介面和型別之間的轉換

go語言中使用介面斷言 type assertions 將介面轉換成另外乙個介面,也可以將介面轉換為另外的型別。格式 i.t i表示乙個介面的型別和t表示乙個型別 斷言的基本格式 t i.t i 代表介面變數,t 代表轉換的目標型別,t 代表轉換後的變數 三種情況 var w io.writer w...

CString Char Byte之間的轉換

在vc中,cstring類的用法形式多樣,豐富多彩.但有時與傳統資料型別之間的轉換成為了很多人的難題.1.如何實現cstring與char 之間的轉換 1 cstring轉換成char cstring m cstr abc char m char def char lp m cstr.getbuff...

進製之間的轉換

今天翻了一本計算機基礎的書籍,其中十進位制 二進位制 八進位制 十六進製制之間的轉換挺有意思的,也容易犯糊塗,特溫故而知新。十進位制數制系統 十進位制數制系統包括 10 個數字 0 1 2 3 4 5 6 7 8 9 基為 10 逢十進一,如3 7 10,20 80 100 二進位制數制系統 計算機...