跳過到頁腳內容
.NET幫助

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

C#中的程式設計經常涉及處理不同類型的資料。 有時,我們需要檢查object是否為某種類型,或者嘗試將其轉換為該類型。 這就是as運算符關鍵字派上用場的地方。 與其密切相關的is運算符協助類型測試和轉換。 在本教程中,我們將探索這個運算符的細節及其使用案例。

了解as運算符

as運算符的基礎

C#中的as運算符關鍵字是一個二元運算符,用於在相容的參考類型或可為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
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.
$vbLabelText   $csharpLabel

在上面的程式碼中,object的物件(C#中所有類型的基本類型)。 我們在編譯時不確定其底層類型。使用string。 如果成功,myStr將保留字串值。 否則,它將保留null值。

它與顯式轉換有何不同?

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

如顯所見,使用as運算符往往更安全,因為您可以避免潛在的執行時錯誤。

與is運算符的關聯

通常,is運算符結合使用,以便在嘗試轉換之前進行類型測試。 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");
}
$vbLabelText   $csharpLabel

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

深入探討:特殊案例和注意事項

可為null的值類型轉換

null值。 然而,透過使它們成為可為null的,您可以給它們賦值null。 as運算符可用於嘗試轉換為可為null的值類型:

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

在這裡,使用者定義的轉換方法允許將一個string處理。

當as不適用

請記住,as運算符不能與值類型一起使用(除非處理可為null的值類型),也不能與涉及顯式方法的使用者定義轉換一起使用。

帶有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;
$vbLabelText   $csharpLabel

在這裡,object中。

拆箱是裝箱的逆向過程,即從object中提取值類型。 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?;
$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
$vbLabelText   $csharpLabel

在上面的程式碼中,arrayObject是一個物件陣列,但實際上包含字串。 使用as運算符,您可以安全地嘗試將其視為字串陣列。

as與LINQ結合

語言整合查詢 (LINQ - 微軟文件) 是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"
$vbLabelText   $csharpLabel

與Iron Suite的整合

Iron Suite為C#開發者提供解決方案是一套高品質的工具,能夠支持C#開發者無縫整合功能,如PDF操作,Excel處理,光學字元識別(OCR),以及條碼生成和讀取。 這些工具,就像我們之前討論is運算符一樣,對於提高開發者在構建健壯應用程式時的效率至關重要。

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是一個光學字元識別工具,允許開發者從圖像中讀取和解釋文本。 將此與我們的教程對接起來,這類似於將一個string或文本數據),使用高級識別功能。

IronBarcode

C# AS(它對開發者的工作原理)圖4 - IronBarcode for .NET: C#的條碼程式庫

在許多商業應用中,處理條碼是不可或缺的。 IronBarcode Tool for Barcode Processing幫助開發者在C#應用程式中生成、讀取和解碼條碼。 將此與我們關於類型轉換的討論對接來看,object的一種形式)翻譯為更具體、可用的數據類型,如字串或產品詳細信息的工具。

結論

C# AS(它對開發者的工作原理)圖5 - Iron Suite for .NET

Iron Suite產品中的每個產品都見證了C#提供的靈活性和強大,尤其是在與我們對類型轉換和類型檢查的討論聯繫時。 這些工具,如is運算符,使開發者能夠高效地轉換和處理資料。

如果您考慮將這些工具中的任何一個整合到您的專案中,需要注意的是,每個產品授權從$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'安全轉換它,確保型別安全並避免例外。

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

Jacob Mellor是Iron Software的首席技術官,也是開創C# PDF技術的前瞻性工程師。作為Iron Software核心代碼庫的原始開發者,他自公司成立以來就塑造了公司的產品架構,並與CEO Cameron Rimington將公司轉型為服務NASA、Tesla以及全球政府機構的50多人公司。

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

他的旗艦作品IronPDF和Iron Suite .NET程式庫全球已獲得超過3000萬次NuGet安裝,他的基礎代碼不斷在全球各地驅動開發者工具。擁有25年以上的商業經驗和41年的編碼專業知識,Jacob仍然專注於推動企業級C#、Java和Python PDF技術的創新,同時指導下一代技術領導者。

Iron Support Team

We're online 24 hours, 5 days a week.
Chat
Email
Call Me