首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >你能在switch表达式中得到被打开的值吗?

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

Stack Overflow用户
提问于 2021-02-11 10:04:22
回答 2查看 48关注 0票数 3

有没有办法做到这一点?

代码语言:javascript
复制
int i = object.GetString() switch
{
    "this" => 1,
    "that" => 2,
    "the other" => 3,
    _ => someMethod([switch value])
}

在switch表达式中使用打开的值?或者我必须这么做

代码语言:javascript
复制
var myString = object.GetString()
int i = myString switch
{
    "this" => 1,
    "that" => 2,
    "the other" => 3,
    _ => someMethod(myString)
}

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

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2021-02-11 10:12:54

这个怎么样?

代码语言:javascript
复制
int i = object.GetString() switch
{
    "this" => 1,
    "that" => 2,
    "the other" => 3,
    { } s => someMethod(s)
}

它会得到除了null之外的任何东西。

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

代码语言:javascript
复制
string s => someMethod(s)
票数 5
EN

Stack Overflow用户

发布于 2021-02-11 10:12:57

是的,这很简单:

代码语言:javascript
复制
int i = object.GetString() switch
{
    "this" => 1,
    "that" => 2,
    "the other" => 3,
    string value => someMethod(value)
};
票数 5
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/66147790

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档