MST

星途 面试题库

面试题:C#模式匹配与switch表达式在复杂数据结构中的应用

给定一个包含多种类型元素的列表List<object> mixedList,其中可能包含整数、字符串、自定义的Person类对象(Person类有Name和Age属性)。请利用C#的模式匹配和switch表达式遍历这个列表,对整数计算平方,对字符串输出其长度,对Person对象输出其姓名和年龄信息。
46.1万 热度难度
编程语言C#

知识考点

AI 面试

面试题答案

一键面试
using System;

class Person
{
    public string Name { get; set; }
    public int Age { get; set; }
}

class Program
{
    static void Main()
    {
        var mixedList = new object[] { 5, "Hello", new Person { Name = "Alice", Age = 30 } };

        foreach (var item in mixedList)
        {
            switch (item)
            {
                case int number:
                    Console.WriteLine($"Square of {number} is {number * number}");
                    break;
                case string str:
                    Console.WriteLine($"Length of '{str}' is {str.Length}");
                    break;
                case Person person:
                    Console.WriteLine($"Person: Name={person.Name}, Age={person.Age}");
                    break;
                default:
                    Console.WriteLine("Unrecognized type");
                    break;
            }
        }
    }
}