跳過到頁腳內容
.NET幫助

C# AS(開發者的工作原理)

在 C# 中編程通常涉及處理不同類型的數據。 有時,我們需要檢查某個對象是否屬於某一特定類型,或者嘗試將其轉換成該類型。 這就是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.
$vbLabelText   $csharpLabel

在上述代碼中,myObj是一個object類型的對象(在 C# 中所有類型的基礎類型)。 在編譯時,我們不確定它的底層類型。使用as運算符來嘗試將myObj作為string來處理。 如果成功,myStr將保存字符串值。 否則,它將保存一個null值。

它與顯式轉型有何不同?

雖然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.
$vbLabelText   $csharpLabel

顯而易見,使用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
$vbLabelText   $csharpLabel

隨著 C# 後來版本中引入模式匹配,is運算符還可以在類型測試通過時執行某些操作。 這通常減少了使用as運算符的需要。

深入探索:特殊情況和考慮因素

可空值類型轉換

其中一個特殊情況是as運算符對可空值類型極為有用。值類型(如intdouble等)不能被賦予null值。 但是,通過使它們可空,可以將 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?)
$vbLabelText   $csharpLabel

引用轉換和用戶自定義轉換

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"
$vbLabelText   $csharpLabel

在這裡,該用戶自定義轉換方法允許Sample類型的對象被視為string

當 as 不適用時

記住,除非涉及到可空值類型,否則as運算符不能與值類型一起使用,也不能與涉及顯式方法的用戶自定義轉換一起使用。

as 運算符的高級情境

使用 as 進行裝箱和拆箱

裝箱是將值類型實例轉換為對象引用的過程。 這是可能的,因為每個值類型都隱式繼承自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
$vbLabelText   $csharpLabel

在這裡,intValue被裝箱到一個object中。

拆箱是裝箱的反向過程,即從object中提取值類型。 as運算符可以用於安全地拆箱值,特別是當你不確定object是否持有你所預期的值類型時。 如果拆箱不成功,表達式結果將為 null。

請考慮以下拆箱轉換示例:

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?)
$vbLabelText   $csharpLabel

處理數組

在 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
$vbLabelText   $csharpLabel

在上述代碼中,arrayObject是一個對象數組,但實際上持有字符串。 使用as運算符,你可以安全地嘗試將其視為字符串數組。

將 as 與 LINQ 結合

集成查詢語言(LINQ - Microsoft Documentation)是 C# 中的一個強大功能,允許你以類似 SQL 的方式查詢集合。 有時,你可能會在集合中檢索到混合類型的對象,然後希望篩選出特定類型。這時,as運算符是個好幫手。

例如,請考慮包含字符串和整數的對象列表。 如果你只想檢索字符串,可以將as運算符與 LINQ 結合使用:

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"
$vbLabelText   $csharpLabel

與 Iron Suite 的集成

Iron Suite 為 C# 開發人員提供解決方案,這是一套高質量工具,使得 C# 開發者能夠無縫集成功能,如 PDF 操作、Excel 處理、光學字符識別(OCR)以及條碼的生成和讀取。 這些工具像我們之前討論的asis運算符一樣,在提高開發人員構建強大應用程序效率方面起著關鍵作用。

IronPDF

C# AS(開發者如何使用)圖 1 - IronPDF for .NET:C# PDF 庫

IronPDF 允許開發者在他們的 C# 應用程序中生成、操作和讀取 PDF 文件。 考慮到我們討論的相關性,假設你有一個參考類型持有一些數據,並希望將這些數據轉換成報告或文檔。 IronPDF 可以將你的應用程序輸出,以類型轉換的方式將其轉換為格式精美的 PDF 文件。

IronXL

C# AS(開發者如何使用)圖 2 - IronXL for .NET:C# Excel 庫

在許多軟件應用程序中處理 Excel 文件是經常需要的。 IronXL for Excel Operations 提供給開發人員讀取、編輯和創建 Excel 試算表的能力,而不需要依賴 Office Interop。在我們之前討論的類型轉換背景下,把IronXL 看成是一種工具,它允許你將數據結構或數據庫條目在 C# 中無縫地轉換成 Excel 格式。

IronOCR

C# AS(開發者如何使用)圖 3 - IronOCR for .NET:C# OCR 庫

Optical Character Recognition with IronOCR 是一個允許開發者從圖像中讀取和解釋文本的光學字符識別工具。 將這與我們的教程連結起來,它類似於使用先進的識別功能將object(在本例中為圖像)轉換為更為具體的類型(string 或文本數據)。

IronBarcode

C# AS(開發者如何使用)圖 4 - IronBarcode for .NET:C# 條碼庫

在許多商業應用中,處理條形碼是不可或缺的。 IronBarcode Tool for Barcode Processing 幫助開發人員在 C# 應用程序中生成、閱讀和解碼條形碼。 相關於我們關於類型轉換的討論,IronBarcode 可以被視為一種工具,將視覺條形碼數據(一種object)轉換為更具體的、可用的數據類型,比如字符串或產品細節。

結論

C# AS(開發者如何使用)圖 5 - Iron Suite for .NET

每個<驚com>Product各出於 Iron Suite 提供 都證明了 C# 提供的靈活性和強大,特別是在我們關於類型轉換和類型檢測的討論中。 這些工具,像asis運算符一樣,為開發者提供了高效轉換和處理數據的能力。

如果你考慮將這些工具集成到你的項目中,值得注意的是每個產品的授權價格從$799開始,並且每個產品均提供試用版 Iron Suite 工具的免費試用。 對於尋求全面解決方案的人士,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'安全轉換它,確保型別安全並避免例外。

Curtis Chau
技術作家

Curtis Chau 擁有卡爾頓大學計算機科學學士學位,專注於前端開發,擅長於 Node.js、TypeScript、JavaScript 和 React。Curtis 熱衷於創建直觀且美觀的用戶界面,喜歡使用現代框架並打造結構良好、視覺吸引人的手冊。

除了開發之外,Curtis 對物聯網 (IoT) 有著濃厚的興趣,探索將硬體和軟體結合的創新方式。在閒暇時間,他喜愛遊戲並構建 Discord 機器人,結合科技與創意的樂趣。