跳至页脚内容
.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操作符非常有用的特殊情况是用于可空值类型。值类型(如int, double等)不能被赋予null值。 但是,通过使它们可为空,您可以为其分配nullas操作符可以用于尝试转换为可空值类型:

// 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 文档)是 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(它对开发人员的工作原理)图 1 - IronPDF for .NET: C# PDF 库

IronPDF 允许开发人员在其 C# 应用程序中生成、操作和读取 PDF 文件。 考虑到与我们的话题的相关性,假设您有一个引用类型保存了一些数据,并且您希望将这些数据转换为报告或文档。 IronPDF可以获取您的应用程序的输出,并以类似于类型转换的方式将其转换为格式良好的 PDF 文档。

了解更多关于 IronXL 是一个 Excel 库,可帮助处理 Excel 文件而无需安装 Excel。

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

处理 Excel 文件是许多软件应用程序中的常见要求。 IronXL for Excel Operations为开发人员提供了读取、编辑和创建 Excel 电子表格的能力,而无需依赖 Office Interop。在我们关于类型转换的讨论中,可以将IronXL视为允许将 C# 中的数据结构或数据库条目无缝转换为 Excel 格式的工具。

光学字符识别 (OCR) 是一种将不同类型的文档转换为可编辑和可搜索数据的技术。

C# AS (How It Works For Developers) 图 3 - IronOCR for .NET: The C# OCR 库

使用 IronOCR 进行光学字符识别是一个光学字符识别工具,允许开发人员从图像中读取和解释文本。 将其与我们的教程相结合,这类似于通过高级识别能力将object(在这种情况下是图像)转换为更具体的类型(string或文本数据)。

开始使用 IronBarcode 是一个专为 .NET 框架设计的条码读取和写入库。

C# AS (How It Works For Developers) 图 4 - IronBarcode for .NET: The C# Barcode Library

在许多商业应用中,处理条形码是必不可少的。 IronBarcode 条形码处理工具帮助开发人员在 C# 应用程序中生成、读取和解码条形码。 与我们关于类型转换的讨论相关,IronBarcode可以被视为将视觉条形码数据(一种object)转换为更具体、可用的数据类型(如字符串或产品详细信息)的工具。

结论

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

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' 运算符允许您在使用 'as' 进行安全转换之前,首先使用 'is' 检查对象类型,从而确保类型安全并避免异常。

Curtis Chau
技术作家

Curtis Chau 拥有卡尔顿大学的计算机科学学士学位,专注于前端开发,精通 Node.js、TypeScript、JavaScript 和 React。他热衷于打造直观且美观的用户界面,喜欢使用现代框架并创建结构良好、视觉吸引力强的手册。

除了开发之外,Curtis 对物联网 (IoT) 有浓厚的兴趣,探索将硬件和软件集成的新方法。在空闲时间,他喜欢玩游戏和构建 Discord 机器人,将他对技术的热爱与创造力相结合。