代码:
namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
//创建list数组,=号右边可省略
List<student>? ts = new();
var StuA = new student("明明子", "1606", 18);
//直接复制更新StuA并赋值给StuB
var StuB = StuA with { Name = "BaiPiaoD" };
ts.Add(StuA);
ts.Add(StuB);
//根据属性判断
if (ts[0] is student or { Name: "明明子" } or { Age: >= 12 })
{
Console.WriteLine("或许捕捉到一只成年明明子");
}
//根据属性判断
if (ts[1] is { Age: > 12 and < 23, Name: "BaiPiaoD" })
{
Console.WriteLine(ts[1].Name + GoodBoy(ts[1].Age));
}
//Switch语法,判断参数age,返回不同的值
string GoodBoy(int age) => age switch
{
< 5 => "崽崽",
< 18 => "小屁孩",
< 50 => "猛男",
_ => "老家伙"
};
}
}
//C#9包含一种称为记录的新类型的类record。与常规类相比,它有许多优点,其中一半与更简洁的语法有关。
public record student(string Name, string Class, int Age);
}