📜  C#7.0 模式匹配

📅  最后修改于: 2020-11-01 03:08:34             🧑  作者: Mango

C#模式匹配

C#模式匹配是一项允许我们对数据或任何对象执行匹配的功能。我们可以使用is表达式和switch语句执行模式匹配。

表达式用于检查对象是否与给定类型兼容。

在下面的示例中,我们正在实现is表达式。

使用示例进行C#模式匹配

using System;
namespace CSharpFeatures
{
    class Student
    {
        public string Name { get; set; } = "Rahul kumar";
    }
    class PatternMatchingExample
    {
        public static void Main(string[] args)
        {
            Student student = new Student();
            if(student is Student)
            {
                Console.WriteLine(student.Name);
            }
        }
    }
}

输出:

Rahul kumar

我们还可以在switch语句中执行模式匹配。请参见以下示例。

切换案例示例2中的C#模式

using System;
namespace CSharpFeatures
{
    class Student
    {
        public string Name { get; set; } = "Rahul kumar";
    }
    class Teacher
    {
        public string Name { get; set; } = "Peter";
        public string Specialization { get; set; } = "Computer Science";
    }
    class PatternMatchingExample
    {
        public static void Main(string[] args)
        {
            Student student = new Student();
            Teacher teacher = new Teacher();
            PatterInSwitch(student);
            PatterInSwitch(teacher);
        }
        public static void PatterInSwitch(object obj)
        {
            switch (obj)
            {
                case Student student:
                    Console.WriteLine(student.Name);
                    break;
                case Teacher teacher:
                    Console.WriteLine(teacher.Name);
                    Console.WriteLine(teacher.Specialization);
                    break;
                default:
                    throw new ArgumentException(
                        message: "Oject is not recognized",
                        paramName: nameof(obj));
            }
        }
    }
}

输出:

Rahul kumar
Peter
Computer Science