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

mas*_*uko 3 c#

有没有办法做到这一点

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

Run Code Online (Sandbox Code Playgroud)

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

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

Run Code Online (Sandbox Code Playgroud)

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

Rod*_*ues 5

那这个呢?

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

它不会得到任何东西null

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

string s => someMethod(s)
Run Code Online (Sandbox Code Playgroud)


Eni*_*ity 5

是的,这很简单:

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