【问题标题】:Using if statements when declaring values of an array声明数组值时使用 if 语句
【发布时间】:2022-11-04 15:15:07
【问题描述】:

我创建了一些代码,如下所示,用于声明数组的值。但是,我知道还有另一种方法可以使用 if 语句来执行此操作,您也可以向我展示这种方式吗? N、Q、L、R 和 K 是有效代码,“默认”代码是给出无效代码(除列出的字母外的任何字母)时。

已将代码放在下面 - 如果需要更多信息,请告诉我:

public void setInfo(string c)
{
    switch (c)
    {
        case "K":
            event_code = event_codes[0];
            break;
        case "L":
            event_code = event_codes[1];
            break;
        case "R":
            event_code = event_codes[2];
            break;
        case "Q":
            event_code = event_codes[3];
            break;
        case "N":
            event_code = event_codes[4];
            break;
        default:
            event_code = "I";
            break;
    }
}

【问题讨论】:

  • 为什么要使用 if 语句?开关做得很好。
  • event_codes 是什么?
  • 它会像开关一样干净表达,诚然。
  • 例如gist.github.com/jskeet/1ca3abb70639411d6b8bceeea86d3882 - 使用一些更传统的名称。
  • 我不会将其更改为 if 子句。不过,在您的情况下,使用Dictionary<char, string> 会更有意义。您可以将字符添加为键,将代码添加为值。之后,您只需说 dict[c] 即可获得所需的值。请记住检查密钥是否存在,如下所示:if (dict.ContainsKey(c))

标签: c# if-statement visual-studio-code


【解决方案1】:

我不会给你代码,因为最好理解使用switchif 语句的过程。

switch 语句只是告诉编译器将提供的参数值与每个 case 语句值进行比较,如果为真,则在该参数和下一个 break 关键字之间运行代码。在break 进一步处理switch 停止。

因此switch 可以被认为是:

switch(s) ---> 是参数s

case "R": ---> 等于“R”

如果然后运行

event_code = event_codes[2];

default ---> s 不等于任何 case 条件所以运行

event_code = "I";

if 子句必须返回逻辑结果,即该语句必须为真或假。

if 结构将是:

if (<some logical test>)
{ // test is true
    <run this code>
}
else
{ //test is false
    <run this code>
}

switch 可以替换为多个ifs,但正如您所见,每个case 都需要一个if

不要忘记 default 子句 - 这是在所有测试条件都失败时运行的代码,并且您需要通过在一个通过其逻辑后不处理更多 if 子句来复制开关的行为测试并运行test is true 部分中的代码。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-29
    • 2012-04-21
    • 2016-05-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多