跳至页脚内容
.NET 帮助

C# AS(开发者如何使用)

在 C# 中编程通常涉及处理不同类型的数据。 有时候,我们需要检查一个object是否为某种类型,或者尝试将其转换为该类型。 这就是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.
$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值。 但是,通过使它们可为空,您可以为其分配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?;
$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运算符不能用于值类型(除非处理可空值类型)或涉及显式方法的用户定义转换。

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 - Microsoft 文档)是 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 集成

为 C# 开发人员提供的 Iron Suite 解决方案是一套高质量工具,使 C# 开发人员能够无缝集成功能,例如 PDF 操作、Excel 处理、光学字符识别 (OCR)、条形码生成和读取。 这些工具,如我们之前讨论的is运算符,对于提高开发人员在构建健壮应用程序方面的效率至关重要。

IronPDF

C# AS(开发人员如何运作)图1 - IronPDF for .NET:C# PDF库

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

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

C# AS(开发人员如何运作)图2 - IronXL for .NET:C# Excel库

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

IronOCR

C# AS(开发人员如何运作)图3 - IronOCR for .NET:C# OCR库

Optical Character Recognition with IronOCR是一个光学字符识别工具,它允许开发人员读取和解释图像中的文本。 将其与我们的教程联系起来,这类似于使用高级识别功能将string或文本数据)。

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

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

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

Jacob Mellor 是 Iron Software 的首席技术官,也是一位开创 C# PDF 技术的有远见的工程师。作为 Iron Software 核心代码库的原始开发者,他从公司成立之初就开始塑造公司的产品架构,与首席执行官 Cameron Rimington 一起将公司转变为一家拥有 50 多名员工的公司,为 NASA、特斯拉和全球政府机构提供服务。

Jacob 拥有曼彻斯特大学土木工程一级荣誉工程学士学位(BEng)(1998-2001 年)。他的旗舰产品 IronPDF 和 Iron Suite for .NET 库在全球的 NuGet 安装量已超过 3000 万次,其基础代码继续为全球使用的开发人员工具提供动力。Jacob 拥有 25 年的商业经验和 41 年的编码专业知识,他一直专注于推动企业级 C#、Java 和 Python PDF 技术的创新,同时指导下一代技术领导者。

Iron Support Team

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