c# - 你能得到在 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)

关于c# - 你能得到在 switch 表达式中被打开的值吗,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66147790/

相关文章:

c# - 意外编辑文件时禁用 Visual Studio 2010 中的自动 checkout

c# - 检测到没有响应的线程并终止它?

c# - mysql数据按时间间隔排序

c# - 这段代码能确保我从一个套接字中读取我想要的所有内容吗?

c# - 如何忽略 [XMLIgnore] 属性

c# - 从集合 Entity Framework 中删除项目

c# - 如何使应用程序适应 Windows 8 中的多种分辨率

c# - "No parameterless constructor defined for this object."用于 Controller 中使用 StructureMap 的 IBus

c# - Windows DPI 设置影响 Graphics.DrawString

c# - 如何将整数转换为它的语言表示形式?