C# 等号右箭头表示什么
经过软糖查询,目前有 3 种用法。
⒈ Lambda运算符。(C# 3.0)
左边是输入参数(如果有),右边是表达式或语句块。所有Lambda表达式都使用Lambda运算符=>,该运算符读作"goes to"。
Lambda表达式x => x * x读作"x goes to x times x"。
⒉ 只读属性的简便写法。(C# 7.0)
Public String 姓名 => "张三";
⒊ 模式匹配增强。(C# 9.0)
✦ Type patterns 类型匹配,判断一个变量的类型
object obj = new int();var type = obj switch {
string => "string",
int => "int",
_ => "obj"};Console.WriteLine(type); // int
12345678
✦ Relational patterns 关系匹配
// Relational patternsvar person1 = new Person("Zhimin Zhang", 40);var inRange = person1 switch {
(_, < 18) => "less than 18",
(_, > 18) => "greater than 18",
(_, 18) => "18 years old!"};Console.WriteLine(inRange); // greater than 1812345678
✦ Conjunctive and patterns 逻辑与匹配
// And patternvar person1 = new Person("Zhimin Zhang", 40);var ageInRange = person1 switch {
(_, < 18) => "less than 18",
("Zhang Zhimin", _) and (_, >= 18) => "Zhimin Zhang is greater than 18"};Console.WriteLine(ageInRange); // Zhimin Zhang is greater than 18
12345678
✦ Disjunctive or patterns 逻辑或匹配
// Or patternvar person1 = new Person("Zhimin Zhang", 40);var ageInRange = person1 switch {
(_, < 18) => "less than 18",
(_, 18) or (_, > 18) => "18 or greater"};Console.WriteLine(ageInRange); // 18 or greater1234567
✦ Negated not patterns 逻辑非匹配
// Not patternvar person1 = new Person("Zhimin Zhang", 40);var meOrNot = person1 switch {
not ("Zhimin Zhang", 40) => "Not me!",
_ => "Me :-)"};Console.WriteLine(meOrNot); // Me :-)
12345678
✦ Parenthesized patterns 带括号的优先级匹配
// Parenthesized patternsvar is10 = new IsNumber(true, 10);var n10 = is10 switch {
((_, > 1 and < 5) and (_, > 5 and < 9)) or (_, 10) => "10",
_ => "not 10"};Console.WriteLine(n10); // 10