为交换机的结果设置变量 [英] Setting a Variable to a Switch's Result

查看:60
本文介绍了为交换机的结果设置变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在C#中,是否可以通过switch表达式设置变量?例如:

In C#, is there a way to set a variable from a switch expression? For example:

var a = switch(b)
{
    case c:
    d;

    case e:
    f;

    default:
    g;
};

是否可以使用其他任何语言?

Is it possible in any other language?

推荐答案

从C#8开始:

是的,在C#8中引入了 switch表达式.就语法而言,示例为:

Yes, switch expressions were introduced in C# 8. In terms of syntax, the example would be:

var a = b switch
{
    c => d,
    e => f,
    _ => g
};

...,其中 c e 必须是有效的 patterns 才能与 b 匹配. _ 代表默认情况.

... where c and e would have to be valid patterns to match against b. _ represents the default case.

在C#8之前:

否, switch 是一个语句,而不是可以求值的表达式.

No, switch is a statement rather than an expression which can be evaluated.

当然,您可以将其提取到另一种方法中:

Of course, you can extract it into another method:

int x = DoSwitch(y);

...

private int DoSwitch(int y)
{
    switch (y)
    {
        case 0: return 10;
        case 1: return 20;
        default: return 5;
    }
}

或者,如果只是简单的常量映射的情况,则可以使用 Dictionary .如果您可以向我们提供有关您要实现的目标的更多信息,我们可能会帮助您找到最惯用的方式.

Alternatively, you could use a Dictionary if it's just a case of simple, constant mappings. If you can give us more information about what you're trying to achieve, we can probably help you work out the most idiomatic way of getting there.

这篇关于为交换机的结果设置变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆