跳過到頁腳內容
.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 值。

與 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.
$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 值。 不過,只要將它們變成 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?)
$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 運算符號不能用於值類型(除非處理的是 nullable 值類型)或涉及顯式方法的使用者定義轉換。

使用 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
$vbLabelText   $csharpLabel

在此,intValue 被框入 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?)
$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 文件) 是 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 整合。

適用於 C# 開發人員的 Iron Suite 解決方案是一套高品質的工具,可讓 C# 開發人員無縫整合 PDF 操作、Excel 處理、光學字元辨識 (OCR) 以及條碼產生和讀取等功能。 這些工具,就像我們之前討論的 asis 運算符一樣,對於提升開發人員建立強大應用程式的效率至關重要。

IronPDF。

C# AS (How It Works For Developers) 圖 1 - IronPDF for .NET:C# PDF Library

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

IronXL。

C# AS (How It Works For Developers) 圖 2 - IronXL for .NET:C# Excel Library

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

IronOCR。

C# AS (How It Works For Developers) 圖 3 - IronOCR for .NET:C# OCR Library

Optical Character Recognition with IronOCR 是一種光學字元識別工具,允許開發人員從影像中讀取並解釋文字。 與我們的教學相連結,它類似於使用進階識別功能將 物件(在本例中為影像)轉換為更特定的類型(字串或文字資料)。

IronBarcode。

C# AS (How It Works For Developers) 圖 4 - IronBarcode for .NET:C# BarCode Library

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

結論

C# AS (How It Works For Developers) 圖 5 - Iron Suite for .NET

Iron套件產品中的每一款產品都證明了 C# 所提供的靈活性和強大功能,尤其是與我們討論的類型轉換和類型檢查相結合的時候。 這些工具,例如 asis 運算符,為開發人員提供了有效轉換和處理資料的能力。

如果您正在考慮將任何這些工具整合到您的專案中,值得注意的是,每一個產品的授權都從 $799 起,而且每一個產品都提供 免費試用 Iron Suite Tools 的機會。 對於那些正在尋找全面解決方案的人,Iron Suite 提供了一個誘人的優惠:您可以 只需購買兩項產品的價格即可獲得 Iron Suite 授權

常見問題解答

as' 運算符號在 C# 開發中扮演什麼角色?

C# 中的 'as' 運算符用於在相容的參照類型或 nullable 類型之間執行安全的類型轉換,如果轉換不成功則返回 null,從而避免異常。

如何在 C# 中安全地處理類型轉換?

您可以使用「as」運算元進行安全的類型轉換,因為當轉換失敗時,它會回傳 null 而不是拋出異常,因此比明確的轉換更安全。

為什麼在某些情況下,'as' 運算符號比明確的轉換更可取?

當您想要避免轉換失敗所導致的異常時,'as' 運算符是首選,因為它會返回 null 而不會產生異常,這與顯式轉換不同。

在 C# 中,'as' 運算符如何與可歸零類型搭配使用?

as' 運算子可與 nullable 類型一起使用,允許安全的轉換,如果物件無法轉換為指定的 nullable 類型,則會回傳 null。

如何在 C# 中使用 IronPDF 進行文件轉換?

IronPDF 可讓 C# 開發人員以程式化的方式將 HTML 轉換為 PDF、處理 PDF 內容以及產生 PDF 檔案,進而增強應用程式中的文件處理能力。

C# 開發人員使用 Iron Suite 有什麼好處?

Iron Suite 提供 IronPDF、IronXL、IronOCR 和 IronBarcode 等工具,讓開發人員能有效率地處理各種格式的資料轉換和處理。

如何使用 C# 從集合中過濾特定類型?

您可以將 'as' 運算符與 LINQ 查詢結合使用,從集合中過濾特定類型,確保只從混合物件清單中選取所需的類型。

在 C# 中結合「is」和「as」運算元的常見用例是什麼?

結合'is「和」as「運算符號可讓您先使用」is「檢查物件的類型,然後再使用」as'安全地轉換物件,以確保類型安全並避免異常。

Jacob Mellor, Team Iron 首席技术官
首席技术官

Jacob Mellor 是 Iron Software 的首席技術官,作為 C# PDF 技術的先鋒工程師。作為 Iron Software 核心代碼的原作者,他自開始以來塑造了公司產品架構,與 CEO Cameron Rimington 一起將其轉變為一家擁有超過 50 名員工的公司,為 NASA、特斯拉 和 全世界政府機構服務。

Jacob 持有曼徹斯特大學土木工程一級榮譽学士工程學位(BEng) (1998-2001)。他於 1999 年在倫敦開設了他的第一家軟件公司,並於 2005 年製作了他的首個 .NET 組件,專注於解決 Microsoft 生態系統內的複雜問題。

他的旗艦產品 IronPDF & Iron Suite .NET 庫在全球 NuGet 被安裝超過 3000 萬次,其基礎代碼繼續為世界各地的開發工具提供動力。擁有 25 年的商業經驗和 41 年的編碼專業知識,Jacob 仍專注於推動企業級 C#、Java 及 Python PDF 技術的創新,同時指導新一代技術領袖。