在Switch语句中使用.StartsWith? [英] Using .StartsWith in a Switch statement?

查看:364
本文介绍了在Switch语句中使用.StartsWith?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在处理Switch语句,并且需要使用两个条件来查看值是否以特定值开头。 Switch语句确实是这样。该错误显示无法将类型bool秘密转换为字符串。

I'm working on a Switch statement and with two of the conditions I need to see if the values start with a specific value. The Switch statement does like this. The error says "cannot covert type bool to string".

有人知道我是否可以在Switch中使用StartsWith,还是需要使用If ... Else语句?

Anyone know if I can use the StartsWith in a Switch or do I need to use If...Else statements?

switch(subArea)
            {
                case "4100":
                case "4101":
                case "4102":
                case "4200":
                    return "ABC";
                case "600A":
                    return "XWZ";
                case subArea.StartsWith("3*"):
                case subArea.StartsWith("03*"):
                    return "123";
                default:
                    return "ABCXYZ123";
            }


推荐答案

您要切换 String subArea.StartsWith()返回 Boolean ,即为什么你做不到。我建议您这样做:

You are switching a String, and subArea.StartsWith() returns a Boolean, that's why you can't do it. I suggest you do it like this:

if (subArea.StartsWith("3*") || subArea.StartsWith("03*"))
    return "123";

switch(subArea)
{
    case "4100":
    case "4101":
    case "4102":
    case "4200":
        return "ABC";
    case "600A":
        return "XWZ";
    default:
        return "ABCXYZ123";
}

结果将相同。

这篇关于在Switch语句中使用.StartsWith?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆