有没有办法做到这一点
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)
关于c# - 你能得到在 switch 表达式中被打开的值吗,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66147790/