事实就是如此:在 C# 中使用 Is 和 As 运算符

发布日期:2026-07-14 02:10:04   来源 : 杭州电子商务研究院    浏览量 :13
杭州电子商务研究院 发布日期:2026-07-14 02:10:04  
13

介绍

C# 开发人员面临的两个最常见任务是类型转换和兼容性检查。当我们想要将某种类型的对象转换为相同类型的另一个对象时,类型转换就派上用场了。兼容性检查是 C# 中支持转换操作的功能。对此的支持以两个运算符的形式出现,一个称为as,另一个称为is。本指南将阐明这两者之间的区别,并帮助您尽可能有效地将它们合并到您的应用程序中。

挑战

我们以下面的代码为例。

      using System;

namespace asitis
{
    public class Student
    {
    }
    class itisas
    {
        static void Main(string[] args)
        {
            Student s = new Student();
            object c = s;
            string r = (string)c;
            Console.ReadKey(); ;
        }
    }
}
    

我们有一个名为Student的空类,如果我们在 Visual Studio 之类的 IDE 中编写此代码,我们将不会收到有关在编译和运行应用程序时发生的传入异常的任何警告。此类错误在运行时发生。

      System.InvalidCastException: 'Unable to cast object of type 'asitis.Student' to type 'System.String'.'
    

没有迹象表明编译器会阻止编译,因为我们试图将一种对象类型转换为不兼容的类型。

我们能做什么呢?第一个也是最常见的方法是try{}catch{}块。大多数开发人员的第一次尝试是包装潜在的关键代码并在发生异常时进行处理。

它看起来应该是这样的:

      using System;

namespace asitis
{
    public class Student
    {
    }
    class itisas
    {
        static void Main(string[] args)
        {
            Student s = new Student();
            object c = s;
            try
                { string r = (string)c; }
            catch
                { Console.WriteLine($"Could not cast {nameof(c)} as string!"); }
            
            Console.ReadKey(); ;
        }
    }
}
    

运行代码之后,我们不会像以前一样出现异常,但是会得到以下输出:

      Could not cast c as string!
    

这个解决方案是完全可行的,但是在大型应用程序中,这会使应用程序更加不稳定,并且更难由开发人员阅读或维护。

一定有更好的方法!

Is 运算符

is运算符将通过简单地针对模式测试表达式来检查表达式的结果是否与给定类型兼容。它有时被称为类型测试运算符,它将检查表达式结果的运行时类型是否与给定类型兼容。针对模式的测试作为 7.0 版的一项功能出现在 C# 中。

让我们通过一个小例子来演示其功能。

      using System;

namespace asitis
{
    public class Student
    { }
    public class Teacher
    { }
    class itisas
    {
        static void testClass(object o)
        {
            if(o is Student)
                { Console.WriteLine($"The instance: {nameof(o)} we recieved as argument is from Student class!"); }
            else if(o is Teacher)
                { Console.WriteLine($"The instance: {nameof(o)} we recieved as argument is from Teacher class!"); }
            else
                { Console.WriteLine($"The instance: {nameof(o)} we recieved as argument is from neither Teacher nor Student class!"); }
        }
        static void Main(string[] args)
        {
            Student s = new Student();
            Teacher t = new Teacher();
            int i = 0;
            testClass(s);
            testClass(t);
            testClass(i);
            Console.ReadKey(); ;
        }
    }
}
    

代码的输出非常容易理解。

      The instance: o we recieved as argument is from Student class!
The instance: o we recieved as argument is from Teacher class!
The instance: o we recieved as argument is from neither Teacher nor Student class!
    

我们基本上有两个骨架类,允许我们创建不同的实例。在我们的主类中,我们有testClass函数,它接受一个任意对象并将其打印到控制台,无论它是StudentTeacher还是两者都不是。

作为操作员

as运算符用于执行兼容类型之间的转换。它的作用与is运算符非常相似,但其工作原理不同。

让我们重用以前的代码来演示其功能。

      using System;

namespace asitis
{
    public class Student
    {
    }
    public class Teacher
    {

    }
    class itisas
    {
        static void Main(string[] args)
        {
            object[] MyObjects = new object[4];
            MyObjects[0] = new Student();
            MyObjects[1] = new Teacher();
            MyObjects[2] = "Student";
            MyObjects[3] = "Teacher";
            for(int i = 0; i < 4; i++)
            {
                string s = MyObjects[i] as string;
                Console.Write($"Inspecting element: {MyObjects[i]}");
                if (s == null)
                    { Console.Write(" ->> Incompatible type"); }
                else
                    { Console.Write(" ->> Compatible type"); }
                Console.WriteLine(", with string!");
            }
            Console.ReadKey(); ;
        }
    }
}
    

我们有之前的两个类,并且我们创建了一个对象列表。这很重要,因为对象类型允许您创建一个可以容纳不同类型对象的列表。然后我们用老师、学生和两个字符串填充它。然后我们迭代数组,在as运算符的帮助下检查其中哪一个与字符串类型兼容。请注意,当我们有一个不兼容的类型时,它不会引发异常,我们只是没有与s变量关联的任何值,该变量的计算结果为null

执行的输出如下所示。

      Inspecting element: asitis.Student ->> Incompatible type, with string!
Inspecting element: asitis.Teacher ->> Incompatible type, with string!
Inspecting element: Student ->> Compatible type, with string!
Inspecting element: Teacher ->> Compatible type, with string!
    

As 和 Is 之间的区别

is运算符用于检查对象的运行时类型是否与给定类型兼容,而as运算符用于执行兼容引用类型或可空类型之间的转换。

is运算是布尔类型,而as运算符不是。

如果给定的对象属于同一类型,则 is运算符返回true ,而当它们与给定类型兼容时,as运算符返回该对象。

如果给定的对象不是同一类型,则 is 运算符返回 false,而如果无法转换,则as运算符返回 null。

is运算符仅用于引用、装箱和拆箱转换,而as运算符仅用于可空、引用和装箱转换。

结论

在本文中,您熟悉了以两个运算符形式实现的类型转换和兼容性检查。这些运算符为您的应用程序带来了更大的灵活性,并允许您开发更强大的程序。我希望这篇文章值得您花时间阅读,并且您找到了想要的内容。感谢您的阅读!

以上内容来自杭州电子商务研究院推送
关注
关于我们
热门推荐
合作伙伴
免责声明:本站部分资讯来源于网络,如有侵权请及时联系客服,我们将尽快处理
Copyright © 2025-2027 ToB产业网址导航 公安备案 浙公网安备33010602013138号 浙ICP备16025413号-9
支持 反馈 关注 数据