你能得到在switch表达式中打开的值吗

c#

有没有办法做到这一点

int i = object.GetString() switch
{
    "this" => 1,
    "that" => 2,
    "the other" => 3,
    _ => someMethod([switch value])
}

使用在 switch 表达式中打开的值?还是我必须这样做

var myString = object.GetString()
int i = myString switch
{
    "this" => 1,
    "that" => 2,
    "the other" => 3,
    _ => someMethod(myString)
}

我知道申报没什么大不了的myString;我只是想知道语法是否存在。

回答

那这个呢?

int i = object.GetString() switch
{
    "this" => 1,
    "that" => 2,
    "the other" => 3,
    { } s => someMethod(s)
}

它不会得到任何东西null

当然,只有当你想在那里捕捉任何类型时它才可用。如果您确定它将是一个string值,并且 someMethod 也需要一个string值,您可以这样做:

string s => someMethod(s)


回答

是的,这很简单:

int i = object.GetString() switch
{
    "this" => 1,
    "that" => 2,
    "the other" => 3,
    string value => someMethod(value)
};


以上是你能得到在switch表达式中打开的值吗的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>