开放的编程资料库

当前位置:我爱分享网 > C#教程 > 正文

C# 开关表达式

在本文中,我们展示了如何在C#中使用switch表达式。

switch表达式在表达式上下文中提供类似switch的语义。当开关臂产生一个值时,它提供了一个简洁的语法。

C#switch表达式值模式

对于值模式,开关臂基于常量值,例如整数或字符串。

Console.Write("Enter a domain name: ");

string? domain = Console.ReadLine();

domain = domain?.Trim().ToLower();

string result = domain switch
{
    "us" => "United States",
    "de" => "Germany",
    "sk" => "Slovakia",
    "hu" => "Hungary",

    _ => "Unknown"
};

Console.WriteLine(result);

在示例中,我们使用switch表达式将国家名称映射到其域名。

$ dotnet run
Enter a domain name: sk
Slovakia
# dotnet run
Enter a domain name: jp
Unknown

C#switch表达式类型模式

数据类型可以是switch表达式的模式。

int age = 23;
string name = "Peter";

List<string> colors = new List<string> {"blue", "khaki", "orange"};
var nums = new int[] {1, 2, 3, 4, 5};

Console.WriteLine(check(age));
Console.WriteLine(check(name));
Console.WriteLine(check(colors));
Console.WriteLine(check(nums));

object check(object val) => val switch 
{
    int => "integer",
    string => "string",
    List<string> => "list of strings",
    Array => "array",
    _ => "unknown"
};

在示例中,我们使用switch表达式找出变量的数据类型。

$ dotnet run
integer
string
list of strings
array

C#switch表达式关系模式

可以使用关系模式构建强大的逻辑。

var nums = new List<int> {-3, 2, 0, 1, 9, -2, 7};

foreach (var num in nums)
{
    var res = num switch 
    {
        < 0 => "negative",
        0 => "zero",
        > 0 => "positive"
    };

    Console.WriteLine($"{num} is {res}");
}

我们有一个整数列表。在foreach循环中,我们遍历列表并使用switch表达式打印值是负数、正数还是零。在switch表达式中,我们使用简单的关系表达式。

$ dotnet run
-3 is negative
2 is positive
0 is zero
1 is positive
9 is positive
-2 is negative
7 is positive

C#switchexpressionwhenguards

使用when守卫为我们的表情臂增加了一些额外的灵活性。

var users = new List<User> 
{
    new ("John", "Doe", 34),
    new ("Roger", "Roe", 44),
    new ("Jane", "Doe", 44),
    new ("Robert", "Molnar", 41),
    new ("Lucia", "Petrovicova", 16),
};

foreach (var user in users)
{
    Console.WriteLine(checkPerson(user));
}

string checkPerson(User u)
{
    return u switch
    {
        { LName: "Doe" } => "Doe family",
        { Age: var age } when age < 18 => "minor person",
        _ => $"{u}"
    };
}

record User(string FName, string LName, int Age);

在示例中,我们使用when守卫来说明18岁以下的用户。

$ dotnet run
Doe family
User { FName = Roger, LName = Roe, Age = 44 }
Doe family
User { FName = Robert, LName = Molnar, Age = 41 }
minor person

C#switch表达式逻辑模式

andor运算符可用于switch表达式。

var users = new List<User> 
{
    new User("Peter Novak", "driver", new DateTime(2000, 12, 1)),
    new User("John Doe", "gardener", new DateTime(1996, 2, 10)),
    new User("Roger Roe", "teacher", new DateTime(1976, 5, 9)),
    new User("Lucia Smith", "student", new DateTime(2007, 8, 18)),
    new User("Roman Green", "retired", new DateTime(1945, 7, 21)),
};

foreach (var user in users)
{
    int age = GetAge(user);

    string res = age switch 
    {
        > 65 => "senior",
        >=18 and <= 64 => "adult",
        < 18 => "minor",
        _ => "unknown",
    };

    Console.WriteLine($"{user.Name} is {res}");
}

int GetAge(User user)
{    
    return (int) Math.Floor((DateTime.Now - user.Dob).TotalDays / 365.25D);
}

record User(string Name, string Occupation, DateTime Dob);

逻辑and运算符用于将成人字符串分配给年龄在18到65岁之间的用户。

$ dotnet run
Peter Novak is adult
John Doe is adult
Roger Roe is adult
Lucia Smith is minor
Roman Green is senior

在下面的示例中,我们有一个or表达式。

var q = @"
WWI started in:

1) 1912
2) 1914
3) 1918
";

Console.WriteLine(q);

var inp = Console.ReadLine();
var ans = int.Parse(inp.Trim());

var res = ans switch
{
    1 or 3 => "Incorrect",
    2 => "correct",
    _ => "unknown option"
};

Console.WriteLine(res);

该示例检查用户的输入并在switch表达式中使用表达式。

C#switch表达式属性模式

对象属性的值可以是switch表达式中的模式。

var products = new List<Product> 
{
    new Product("Product A", 70m, 1, 10),
    new Product("Product B", 50m, 3, 15),
    new Product("Product C", 35m, 2, 20),
};

foreach (var product in products)
{
    Decimal sum = product switch 
    {
        Product { Quantity: 2 } => 
                product.Price * product.Quantity * (1 - product.Discount/100m),
        _ => product.Price * product.Quantity,
    };

    Console.WriteLine($"The final sum for {product.Name} is {sum}");
}

record Product(string Name, decimal Price, int Quantity, int Discount);

在示例中,如果我们购买了两件产品,我们将对产品的价格应用折扣。

$ dotnet run
The final sum for Product A is 70
The final sum for Product B is 150
The final sum for Product C is 56.0

对产品C应用了20%的折扣。

C#switch表达式元组模式

switch表达式可以使用元组模式。

while (true)
{
    var menu = "Select: \n1 -> rock\n2 -> paper\n3 -> scissors\n4 -> finish";
    Console.WriteLine(menu);

    string[] options = {"rock", "paper", "scissors"};

    int val;

    try {
        
        var line = Console.ReadLine();
        if (string.IsNullOrEmpty(line))
        {
            Console.WriteLine("Invalid choice");
            continue;
        }

        val = int.Parse(line);
    } catch (FormatException)
    {
        Console.WriteLine("Invalid choice");
        continue;
    }

    if (val == 4)
    {
        break;
    }

    if (val < 1 || val > 4)
    {
        Console.WriteLine("Invalid choice");
        continue;
    }

    string human = options[val-1];

    var rnd = new Random();
    int n = rnd.Next(0, 3);

    string computer = options[n];

    Console.WriteLine($"I have {computer}, you have {human}");

    var res = RockPaperScissors(human, computer);

    Console.WriteLine(res);
}

Console.WriteLine("game finished");


string RockPaperScissors(string human, string computer) => (human, computer) switch
{
    ("rock", "paper") => "Rock is covered by paper. You loose",
    ("rock", "scissors") => "Rock breaks scissors. You win.",
    ("paper", "rock") => "Paper covers rock. You win.",
    ("paper", "scissors") => "Paper is cut by scissors. You loose.",
    ("scissors", "rock") => "Scissors are broken by rock. You loose.",
    ("scissors", "paper") => "Scissors cut paper. You win.",
    (_, _) => "tie"
};

我们有一个使用元组表达式的剪刀石头布游戏。

string RockPaperScissors(string human, string computer) => (human, computer) switch
{
    ("rock", "paper") => "Rock is covered by paper. You loose",
    ("rock", "scissors") => "Rock breaks scissors. You win.",
...

根据人类和计算机的选择,我们形成元组,这些元组用作开关表达式中的模式以得出游戏结论。

$ dotnet run
Select: 
1 -> rock
2 -> paper
3 -> scissors
4 -> finish
1
I have rock, you have rock
tie
Select: 
1 -> rock
2 -> paper
3 -> scissors
4 -> finish
2
I have paper, you have paper
tie
Select: 
1 -> rock
2 -> paper
3 -> scissors
4 -> finish
3
I have paper, you have scissors
Scissors cut paper. You win.
Select: 
1 -> rock
2 -> paper
3 -> scissors
4 -> finish
4
game finished

在本文中,我们介绍了C#switch表达式。

列出所有C#教程。

未经允许不得转载:我爱分享网 » C# 开关表达式

感觉很棒!可以赞赏支持我哟~

赞(0) 打赏