C# AS(開發者的工作原理)
C# 程式設計通常會涉及不同類型的資料。 有時,我們需要檢查 object 是否屬於某種類型,或嘗試將其轉換為該類型。 這時as 運算子關鍵字就派上用場了。 與其近親一樣,is 運算子有助於類型測試和轉換。 在本教程中,我們將探討此操作符的複雜性及其使用案例。
瞭解 as 運算符號
as 運算子的基礎知識
C# 中的 as 運算子關鍵字是一個二元運算符,用於在相容的引用類型或可空類型之間執行某些轉換。以下程式碼提供了一個簡單的範例:
// Declare an object that holds a string
object myObj = "Hello, World!";
// Use the 'as' operator to attempt to convert 'myObj' to a string
string myStr = myObj as string;
// myStr will hold the string value "Hello, World!" if the conversion is successful;
// otherwise, it will be null.
// Declare an object that holds a string
object myObj = "Hello, World!";
// Use the 'as' operator to attempt to convert 'myObj' to a string
string myStr = myObj as string;
// myStr will hold the string value "Hello, World!" if the conversion is successful;
// otherwise, it will be null.
' Declare an object that holds a string
Dim myObj As Object = "Hello, World!"
' Use the 'as' operator to attempt to convert 'myObj' to a string
Dim myStr As String = TryCast(myObj, String)
' myStr will hold the string value "Hello, World!" if the conversion is successful;
' otherwise, it will be null.
在上面的程式碼中,myObj 是 object 類型的物件(C# 中所有類型的基本類型)。 我們無法確定其在編譯時的底層類型。使用 as 運算子嘗試將 myObj 視為 string。 如果成功,myStr 將保存字串值。 否則,它將保存 null 值。
與 Explicit Cast 有何不同?
雖然 as 運算子和顯式類型轉換都服務於類似的目的,但它們之間存在一個關鍵區別。 如果明確的轉換失敗,就會拋出異常。 另一方面,如果 as 運算子嘗試從一種類型轉換為另一種類型失敗,則該運算子會傳回 null 值,而不是引發異常。 讓我們用以下的程式碼範例來了解:
object someValue = 12345;
string castResult;
// Using explicit cast
try {
castResult = (string)someValue; // This will throw an exception since the cast fails.
}
catch(Exception ex) {
castResult = null; // The result is set to null if an exception is caught.
}
// Using the 'as' operator
string asResult = someValue as string; // No exception, but 'asResult' will be null since the cast fails.
object someValue = 12345;
string castResult;
// Using explicit cast
try {
castResult = (string)someValue; // This will throw an exception since the cast fails.
}
catch(Exception ex) {
castResult = null; // The result is set to null if an exception is caught.
}
// Using the 'as' operator
string asResult = someValue as string; // No exception, but 'asResult' will be null since the cast fails.
Dim someValue As Object = 12345
Dim castResult As String
' Using explicit cast
Try
castResult = DirectCast(someValue, String) ' This will throw an exception since the cast fails.
Catch ex As Exception
castResult = Nothing ' The result is set to null if an exception is caught.
End Try
' Using the 'as' operator
Dim asResult As String = TryCast(someValue, String) ' No exception, but 'asResult' will be null since the cast fails.
顯然,使用 as 運算子通常更安全,因為它可以避免潛在的運行時錯誤。
與 is 運算符號的關係
通常,在嘗試轉換之前,會將 as 運算子與 is 運算子結合使用,以進行類型測試。 is 運算子檢查提供的物件是否為給定的類型,如果是,則傳回 true,否則傳回 false。
以下的程式碼範例說明了這一點:
object testObject = "This is a string";
// Check if testObject is of type string
if (testObject is string) {
// If true, convert testObject to string using 'as'
string result = testObject as string;
Console.WriteLine(result); // Outputs: This is a string
} else {
Console.WriteLine("Not a string");
}
object testObject = "This is a string";
// Check if testObject is of type string
if (testObject is string) {
// If true, convert testObject to string using 'as'
string result = testObject as string;
Console.WriteLine(result); // Outputs: This is a string
} else {
Console.WriteLine("Not a string");
}
Dim testObject As Object = "This is a string"
' Check if testObject is of type string
If TypeOf testObject Is String Then
' If true, convert testObject to string using 'as'
Dim result As String = TryCast(testObject, String)
Console.WriteLine(result) ' Outputs: This is a string
Else
Console.WriteLine("Not a string")
End If
隨著 C# 後續版本中引入模式匹配,如果類型測試通過,is 運算子還可以執行某些操作。 這通常減少了使用 as 運算子的需要。
深入探討:特殊情況與注意事項
可空值類型轉換
as 運算子在可空值類型中非常有用。值類型(如 int、double 等)不能被賦予 null 值。 不過,只要將它們變成 nullable,就可以將 null 指派給它們。 可以使用 as 運算子嘗試轉換為可空值類型:
// Declare a nullable integer
int? nullableInt = 10;
// Box the nullable int
object objInt = nullableInt;
// Attempt to unbox using 'as' to a nullable int type
int? resultInt = objInt as int?;
// Declare a nullable integer
int? nullableInt = 10;
// Box the nullable int
object objInt = nullableInt;
// Attempt to unbox using 'as' to a nullable int type
int? resultInt = objInt as int?;
' Declare a nullable integer
Dim nullableInt? As Integer = 10
' Box the nullable int
Dim objInt As Object = nullableInt
' Attempt to unbox using 'as' to a nullable int type
Dim resultInt? As Integer = CType(objInt, Integer?)
參考轉換和使用者定義轉換
as 運算子支援引用轉換(在相關引用類型之間)和使用者定義的轉換。 使用者定義的轉換是指在您的類別中使用特殊轉換方法定義的轉換。
考慮以下使用者定義轉換的程式碼:
class Sample {
// Define an implicit conversion from Sample to string
public static implicit operator string(Sample s) {
return "Converted to String";
}
}
Sample sampleObject = new Sample();
// Use 'as' to convert 'sampleObject' to string
string conversionResult = sampleObject as string;
// conversionResult will hold "Converted to String"
class Sample {
// Define an implicit conversion from Sample to string
public static implicit operator string(Sample s) {
return "Converted to String";
}
}
Sample sampleObject = new Sample();
// Use 'as' to convert 'sampleObject' to string
string conversionResult = sampleObject as string;
// conversionResult will hold "Converted to String"
Friend Class Sample
' Define an implicit conversion from Sample to string
Public Shared Widening Operator CType(ByVal s As Sample) As String
Return "Converted to String"
End Operator
End Class
Private sampleObject As New Sample()
' Use 'as' to convert 'sampleObject' to string
Private conversionResult As String = TryCast(sampleObject, String)
' conversionResult will hold "Converted to String"
在這裡,使用者定義的轉換方法允許將 Sample 類型的物件視為 string 類型。
不適用時
請記住,as 運算子不能用於值類型(除非處理可為空的值類型)或涉及明確方法的使用者定義轉換。
使用 as 操作符的進階方案。
以 as 開箱和拆箱
Boxing 是將值類型實例轉換為物件參照的過程。 這是因為每個值類型都隱式地繼承自 object。 當你裝箱一個值類型時,你要把它包裝在 object 中。
請考慮以下代碼的拳擊轉換:
int intValue = 42;
// Box the value type to an object
object boxedValue = intValue;
int intValue = 42;
// Box the value type to an object
object boxedValue = intValue;
Dim intValue As Integer = 42
' Box the value type to an object
Dim boxedValue As Object = intValue
這裡,intValue 被裝進 object 中。
拆箱是裝箱的逆過程,即從 object 中提取值類型。 as 運算子可用於安全地拆箱值,尤其是在您不確定 object 是否具有您期望的值類型時。 如果開箱不成功,表達結果將為空。
請考慮以下開箱轉換的範例:
object obj = 42;
// Attempt to unbox using 'as' to a nullable int type
int? result = obj as int?;
object obj = 42;
// Attempt to unbox using 'as' to a nullable int type
int? result = obj as int?;
Dim obj As Object = 42
' Attempt to unbox using 'as' to a nullable int type
Dim result? As Integer = CType(obj, Integer?)
使用陣列工作
陣列是 C# 中的參考類型。 有時,您可能需要確定 object 是否為特定類型的數組,然後對其進行處理。 這裡也可以使用 as 運算子。
請考慮以下程式碼:
object[] arrayObject = new string[] { "one", "two", "three" };
// Attempt to cast to a string array using 'as'
string[] stringArray = arrayObject as string[];
// stringArray will hold the array of strings if successful
object[] arrayObject = new string[] { "one", "two", "three" };
// Attempt to cast to a string array using 'as'
string[] stringArray = arrayObject as string[];
// stringArray will hold the array of strings if successful
Dim arrayObject() As Object = New String() { "one", "two", "three" }
' Attempt to cast to a string array using 'as'
Dim stringArray() As String = TryCast(arrayObject, String())
' stringArray will hold the array of strings if successful
在上面的程式碼中,arrayObject 是一個物件數組,但實際上保存的是字串。 使用 as 運算符,您可以安全地嘗試將其視為字串陣列。
將 as 與 LINQ 結合使用
語言整合查詢 (LINQ - Microsoft 文件) 是 C# 中的一項強大功能,可讓您以類似 SQL 的方式查詢集合。 有時,您可能需要從集合中檢索混合類型的對象,並希望篩選出特定類型。這時,as 運算子就非常有用。
例如,考慮一個包含字串和整數的物件清單。 如果只想檢索字串,可以結合 LINQ 使用 as 運算子:
var mixedList = new List<object> { "Hello", 42, "World", 100 };
// Use LINQ to select only strings from mixedList
var stringValues = mixedList
.Select(item => item as string)
.Where(item => item != null)
.ToList();
// stringValues will contain "Hello" and "World"
var mixedList = new List<object> { "Hello", 42, "World", 100 };
// Use LINQ to select only strings from mixedList
var stringValues = mixedList
.Select(item => item as string)
.Where(item => item != null)
.ToList();
// stringValues will contain "Hello" and "World"
Dim mixedList = New List(Of Object) From {"Hello", 42, "World", 100}
' Use LINQ to select only strings from mixedList
Dim stringValues = mixedList.Select(Function(item) TryCast(item, String)).Where(Function(item) item IsNot Nothing).ToList()
' stringValues will contain "Hello" and "World"
與 Iron Suite 整合。
適用於 C# 開發人員的 Iron Suite 解決方案是一套高品質的工具,可讓 C# 開發人員無縫整合 PDF 操作、Excel 處理、光學字元辨識 (OCR) 以及條碼產生和讀取等功能。 這些工具,就像我們之前討論的 as 和 is 運算子一樣,對於提高開發人員建立健全應用程式的效率至關重要。
IronPDF。

IronPDF 可讓開發人員在其 C# 應用程式中產生、處理和讀取 PDF 檔案。 考慮到與我們主題的相關性,假設您有一個持有某些資料的參考類型,而您想要將這些資料轉換成報告或文件。 IronPDF 可以取得應用程式的輸出,並以類似於類型轉換的方式將其轉換為格式良好的 PDF 文件。
IronXL。

處理 Excel 檔案是許多軟體應用程式的常見需求。 IronXL for Excel Operations使開發人員能夠讀取、編輯和建立 Excel 電子表格,而無需依賴 Office Interop。在我們討論類型轉換的背景下,可以將 IronXL 理解為一種工具,它允許您將 C# 中的資料結構或資料庫條目無縫轉換為 Excel 格式。
IronOCR。

Optical Character Recognition with IronOCR是一款光學字元辨識工具,可讓開發人員讀取和解釋影像中的文字。 將此與我們的教程聯繫起來,它類似於使用高級識別功能將 object(在本例中是圖像)轉換為更具體的類型(string 或文字資料)。
IronBarcode。

在許多商業應用程式中,處理 BarCode 是不可或缺的。 IronBarcode Tool for Barcode Processing幫助開發人員在 C# 應用程式中產生、讀取和解碼條碼。 與我們討論的類型轉換有關,IronBarcode 可以被視為一種工具,它將視覺條碼資料(object 的一種形式)轉換為更具體、更可用的資料類型,例如字串或產品詳細資訊。
結論

Iron套件產品中的每一款產品都證明了 C# 所提供的靈活性和強大功能,尤其是與我們討論的類型轉換和類型檢查相結合的時候。 這些工具,如 as 和 is 運算符,為開發人員提供了高效轉換和處理資料的能力。
如果您正在考慮將這些工具整合到您的專案中,值得注意的是,每個產品授權都從 $999 開始,並且每個產品都提供Iron Suite Tools 的免費試用版。 對於尋求全面解決方案的人來說,Iron Suite 提供了一個誘人的優惠:您只需支付兩款產品的價格即可獲得 Iron Suite 授權。
常見問題解答
在C#開發中,'as'運算子的作用是什麼?
C#中的'as'運算子用於在相容的參考型別或可空型別之間進行安全的型別轉換,如果轉換不成功則返回null,從而避免例外。
你如何在C#中安全地處理型別轉換?
你可以使用'as'運算子進行安全的型別轉換,因為它在轉換失敗時返回null而不是拋出例外,這使其比顯式轉型更安全。
為什麼在某些情況下,'as'運算子比顯式轉型更受青睞?
當你想要避免因轉換失敗而引發的例外時,'as'運算子更受青睞,因為它返回null而不是拋出例外,這與顯式轉型不同。
C#中的'as'運算子如何處理可空型別?
可以將'as'運算子用於可空型別,讓安全轉換成為可能,如果物件無法被轉換為指定的可空型別,則返回null。
如何在C#中使用IronPDF進行文件轉換?
IronPDF讓C#開發人員可以將HTML轉換為PDF,操作PDF內容,並以程式方式生成PDF檔案,提高應用程式中的文件處理能力。
使用Iron Suite對C#開發人員有哪些優勢?
Iron Suite提供像IronPDF, IronXL, IronOCR和IronBarcode等工具,讓開發人員能夠高效處理各種格式的數據轉換和操作。
如何使用C#來篩選集合中特定型別的項目?
你可以將'as'運算子與LINQ查詢結合使用,以篩選集合中特定型別的項目,確保從混合物件列表中選擇所需的型別。
在C#中,結合使用'is'和'as'運算子的常見用例是什麼?
結合使用'is'和'as'運算子可以讓你先用'is'檢查物件的型別,再用'as'安全轉換它,確保型別安全並避免例外。



