预期值为

时间:2018-02-18 00:23:23

标签: c#

我在这里遇到了问题。

void Sre_Reconhecimento(object sender, SpeechRecognizedEventArgs e)
    {
        string text = System.IO.File.ReadAllText(@"C:\Users\ADMIN25\Desktop\testing.txt");
        string[] words = text.Split(',');
        switch (e.Result.Text)
        {

            case words[0]:
                MessageBox.Show("works!");
                break;
            case words[1]:
                MessageBox.Show("works too!");
                break;
        }

    }

当我试图运行该程序时,我收到此错误:预计会有一个常量值。

如何在不使用 if / elseif case 的情况下修复它?

2 个答案:

答案 0 :(得分:1)

你不能像这样动态使用switch语句,因为它在编译时需要constant

然而

  • 您可以使用if语句的集合,

  • 您还可以使用Action

  • 字典

〔实施例

dict = new Dictionary<string, Action>()
        {
            {"Standard", CreateStudySummaryView},
            {"By Group", CreateStudySummaryByGroupView},
            {"By Group/Time", CreateViewGroupByHour}
        };

dict[value].Invoke();

答案 1 :(得分:0)

您应该使用if / else。

执行此操作

但是,如果由于某种原因你真的想要使用开关,你可以通过模式加工来做到这一点。

e.g。

void Main()
{
    string[] words = {"Foo", "Bar", "Quax"};
    var word = "Bar";

    switch(word)
    {
        case string w when w == words[0]:
            MessageBox.Show($"word was {words[0]}");
            break;
        case string w when w == words[1]:
            MessageBox.Show($"word was {words[1]}");
            break;
    }   
}

真的,在这里使用if / else。我不认为切换适合这种用例。

相关问题