.NET 幫助

C# AS(對開發人員的運作方式)

發佈 2023年11月22日
分享:

在 C# 中編程經常涉及不同類型的數據。有時,我們需要檢查 object 是否屬於某種類型,或者嘗試將其轉換為該類型。這時 as 運算子關鍵字 派上了用場。以及它的近親,is operator 在類型測試和轉換中提供幫助。在本教程中,我們將探討這個運算符的細節及其使用案例。

了解 as 運算子

as 運算符的基本知識

as 運算符關鍵字在 C# 中是一個二元運算符,用於在相容的引用型別或可空型別之間執行某些轉換。以下程式碼提供了一個簡單的示範:

object obj = "hello world";
string str = obj as string;

if (str != null)
{
    Console.WriteLine(str);
}
else
{
    Console.WriteLine("conversion failed");
}
object obj = "hello world";
string str = obj as string;

if (str != null)
{
    Console.WriteLine(str);
}
else
{
    Console.WriteLine("conversion failed");
}
Dim obj As Object = "hello world"
Dim str As String = TryCast(obj, String)

If str IsNot Nothing Then
	Console.WriteLine(str)
Else
	Console.WriteLine("conversion failed")
End If
VB   C#
object myObj = "Hello, World!";
string myStr = myObj as string;
object myObj = "Hello, World!";
string myStr = myObj as string;
Dim myObj As Object = "Hello, World!"
Dim myStr As String = TryCast(myObj, String)
VB   C#

在上述程式碼中,myObj 是類型為 object 的物件 (C#中所有類型的基礎類型)我們在編譯時並不確定它的底層類型。as 操作符被用來嘗試將 myObj 作為 string 處理。如果成功,myStr 將持有字符串值。否則,它將持有 null 值

與顯式轉換有何不同?

雖然as-運算符和顯式轉換都有類似的用途,但有一個關鍵區別。如果顯式轉換失敗,它會引發異常。另一方面,如果as運算符從一種類型到另一種類型的轉換嘗試失敗,該運算符會返回空值而不是引發異常。讓我們通過以下代碼示例來理解這一點:

object someValue = 12345;

// Using explicit cast
string castResult;
try {
    castResult = (string)someValue; // This will throw an exception since the cast fails.
}
catch(Exception ex) {
    castResult = null;
}

// Using the as operator
string asResult = someValue as string; // No exception, but asResult will be null since the cast fails.
object someValue = 12345;

// Using explicit cast
string castResult;
try {
    castResult = (string)someValue; // This will throw an exception since the cast fails.
}
catch(Exception ex) {
    castResult = null;
}

// 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

' Using explicit cast
Dim castResult As String
Try
	castResult = DirectCast(someValue, String) ' This will throw an exception since the cast fails.
Catch ex As Exception
	castResult = Nothing
End Try

' Using the as operator
Dim asResult As String = TryCast(someValue, String) ' No exception, but asResult will be null since the cast fails.
VB   C#

顯然地,使用 as 運算符通常更安全,因為你可以避免潛在的運行時錯誤。

與 is 運算子的連接

通常,as 運算子is 運算子 一起使用,用於在嘗試轉換之前進行類型測試。 is 運算子 會檢查提供的對象是否為給定類型,若是則返回 true,否則返回 false。

以下代碼範例說明了這一點:

object testObject = "This is a string";

if(testObject is string) {
    string result = testObject as string;
    Console.WriteLine(result);
} else {
    Console.WriteLine("Not a string");
}
object testObject = "This is a string";

if(testObject is string) {
    string result = testObject as string;
    Console.WriteLine(result);
} else {
    Console.WriteLine("Not a string");
}
Dim testObject As Object = "This is a string"

If TypeOf testObject Is String Then
	Dim result As String = TryCast(testObject, String)
	Console.WriteLine(result)
Else
	Console.WriteLine("Not a string")
End If
VB   C#

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

深入探討 特殊情況與考慮因素

可空值類型轉換

as 運算符在某些特殊情況下,相當有價值,其中之一是可空值類型。值類型 (如 intdouble 等。) 不能被指定為null值。但是,通過使它們可為 null,可以將 null 賦值給它們。as 運算符可用於嘗試轉換為可為 null 的類型:

int? nullableInt = 10;
object objInt = nullableInt;
int? resultInt = objInt as int?;
int? nullableInt = 10;
object objInt = nullableInt;
int? resultInt = objInt as int?;
Dim nullableInt? As Integer = 10
Dim objInt As Object = nullableInt
Dim resultInt? As Integer = CType(objInt, Integer?)
VB   C#

引用轉換和使用者定義轉換

as 運算子支援引用轉換 (相關引用類型之間) 和用户定义的转换。用户定义的转换是那些在类中使用特殊转换方法定义的转换。

请考虑以下用户定义转换的代码:

class Sample {
    public static implicit operator string(Sample s) {
        return "Converted to String";
    }
}

Sample sampleObject = new Sample();
string conversionResult = sampleObject as string;
class Sample {
    public static implicit operator string(Sample s) {
        return "Converted to String";
    }
}

Sample sampleObject = new Sample();
string conversionResult = sampleObject as string;
Friend Class Sample
	Public Shared Widening Operator CType(ByVal s As Sample) As String
		Return "Converted to String"
	End Operator
End Class

Private sampleObject As New Sample()
Private conversionResult As String = TryCast(sampleObject, String)
VB   C#

這裡,自定義轉換方法允許將 Sample 類型的物件當作 string 來處理。

as 不適用時

請記住,as 運算符無法用於值類型 (除非處理可空值類型) 或者使用涉及明確方法的用戶自定義轉換。

使用 as 運算子的進階情境

使用 as 進行裝箱和拆箱

裝箱是將值類型實例轉換為物件引用的過程。這是因為每個值類型都隱式繼承自 object。當你將一個值類型進行裝箱時,你會把它包裝在一個 object 裡面。

請考慮以下的裝箱轉換代碼:

int intValue = 42;
object boxedValue = intValue;
int intValue = 42;
object boxedValue = intValue;
Dim intValue As Integer = 42
Dim boxedValue As Object = intValue
VB   C#

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

拆箱是裝箱的逆過程,即從 object 中提取值類型。可以使用 as 操作符來安全的拆箱值,特別是在你不確定 object 是否包含你期望的值類型時。如果拆箱不成功,表達式結果將為 null。

考慮以下拆箱轉換的例子:

object obj = 42;
int? result = obj as int?;
object obj = 42;
int? result = obj as int?;
Dim obj As Object = 42
Dim result? As Integer = CType(obj, Integer?)
VB   C#

使用陣列

在 C# 中,陣列是參考類型。有時候,您可能需要判斷一個 object 是否是特定類型的陣列,然後進行操作。as 運算符可以在這裡幫助您。

請考慮以下代碼:


    object [] arrayObject = new string [] { "one", "two", "three" };
    string [] stringArray = arrayObject as string [];

    object [] arrayObject = new string [] { "one", "two", "three" };
    string [] stringArray = arrayObject as string [];
Dim arrayObject() As Object = New String () { "one", "two", "three" }
	Dim stringArray() As String = TryCast(arrayObject, String())
VB   C#

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

as與LINQ結合使用

語言集成查詢 (LINQ) 在 C# 中是一個強大的功能,讓您可以以類似 SQL 的方式查詢集合。有時,您可能會在集合中檢索到混合的對象類型並希望過濾出特定的類型。在這裡,as 運算符可以非常方便。

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

var mixedList = new List<object> { "Hello", 42, "World", 100 };
var stringValues = mixedList
    .Select(item => item as string)
    .Where(item => item != null)
    .ToList();
var mixedList = new List<object> { "Hello", 42, "World", 100 };
var stringValues = mixedList
    .Select(item => item as string)
    .Where(item => item != null)
    .ToList();
Dim mixedList = New List(Of Object) From {"Hello", 42, "World", 100}
Dim stringValues = mixedList.Select(Function(item) TryCast(item, String)).Where(Function(item) item IsNot Nothing).ToList()
VB   C#

與 Iron Suite 整合

Iron Suite 是一套高品質工具,能夠使C#開發人員無縫整合如PDF操作、Excel處理、光學字符識別等功能。 (光學字符識別)條碼生成和讀取。這些工具,如我們之前討論的 asis 運算子一樣,對於提高開發人員構建可靠應用程序的效率至關重要。

IronPDF

C# AS(開發人員指南)圖 1 - IronPDF for .NET:C# 的 PDF 庫

IronPDF 允許開發人員在其 C# 應用程式中生成、操作和讀取 PDF 文件。考慮到與我們主題的相關性,假設您有一個包含一些數據的參考類型,並且您想將這些數據轉換成報告或文檔。IronPDF 可以將您的應用程式輸出,類似於類型轉換的方式,轉換成格式良好的 PDF 文件。

IronXL

C# 使用(如何對開發者運作)圖 2 - IronXL for .NET:C# Excel 函式庫

在許多軟體應用程式中,處理 Excel 檔案是經常性的需求。 IronXL 為開發人員提供讀取、編輯和創建Excel電子表格的能力,而無需依賴Office Interop。在我們關於類型轉換的討論中,可以將IronXL視為一個可以讓您將C#中的數據結構或數據庫條目無縫轉換為Excel格式的工具。

IronOCR

C# AS(對開發人員的工作原理)圖 3 - IronOCR for .NET:C# OCR 函式庫

IronOCR 是一個光學字符識別工具,允許開發者從圖片中讀取和解釋文本。連接這個到我們的教程,就像轉換一個 object (在這種情況下,一張圖片) 到更具体的类型 (string 或文本數據) 使用先進的識別能力。

IronBarcode

C# AS(它如何為開發人員運作)圖 4 - IronBarcode for .NET:C# 條碼庫

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

結論

C# 作為(它如何為開發人員工作)圖 5 - Iron Suite for .NET

Iron Software 中的每個產品 Iron Suite 是 C# 的靈活性和強大功能的見證,特別是當我們討論類型轉換和類型檢查時。這些工具,如 asis 運算符,為開發人員提供了高效轉換和處理數據的能力。

如果你考慮將任何這些工具集成到你的項目中,值得注意的是每個產品授權從 $liteLicense 開始,並且每個產品都提供一個 免費試用. 對於尋求綜合解決方案的人而言,Iron Suite 提供了一個誘人的優惠:您可以 購買整套套件 僅需兩款產品的價格。

< 上一頁
C# 表單(對開發人員的運作方式)
下一個 >
C# 資料類型(如何為開發人員工作)

準備開始了嗎? 版本: 2024.10 剛剛發布

免費 NuGet 下載 總下載次數: 10,993,239 查看許可證 >