【问题标题】:c# - case statement for logical operatorsc# - 逻辑运算符的 case 语句
【发布时间】:2015-06-02 23:14:59
【问题描述】:

我收到“无法将字符串隐式转换为字符”错误。我正在尝试以下代码,我应该如何在

char test1;
    switch(test1)
    {
       case '+':
        //do something
        break;

      case '-' : case '*' : case '<=' :
       //method1
       break

    method 1:

    private void method1(char test2)

    {
      if(test2 == '+' || test2 == '*' || test2.ToString() == "<=")
       {
         token.Add(test2.ToString());
       }
    }

好的,我有一个这样的方法:

private void Method1(char test2)
{
  if(test2 == '+' || test2 == '-' || test2 == '/' || test2 == '*')
    {
       //code
       tokens.add(test2);
    }

char test1;
        switch(test1)
        {
           case '+': case '-' : case '*': case '/':
            Method1(test1);
            break;

如果有像 (a+b)*(a-b) 这样的表达式,我正在尝试获取令牌。标记是这里的字符串列表。但是,我在这里还要做的是检查表达式中是否存在逻辑运算符...例如:(a+b)=、==、!=)并在switch case 语句。

【问题讨论】:

  • 修复您的代码。此代码无法按原样编译。
  • 如果你有一个字符,那怎么可能是两个字符?首先,检查没有意义。你真正追求的是什么?
  • 顺便问一下,你怎么指望test2.ToString()等于"
  • 在您的 switch 语句中,您有一个带有 '
  • 您可能需要在任何地方使用string,而不是char

标签: c#


【解决方案1】:

您可以使用 actionDictionary 来代替 switch case 语句:

private void Test(string operant)
{
    Dictionary<string, Action> actionMap = new Dictionary<string, Action>();
    // map operant to action methods
    actionMap.Add("+", new Action(AddToken));
    actionMap.Add("-", new Action(AddToken));
    actionMap.Add("*", new Action(AddToken));
    actionMap.Add(">=", () =>
    {
        // anynomous method
        token.Add(">=");
    });
    actionMap.Add("/", new Action(Divide));
    actionMap.Add("<=", new Action(LessThanOrEqual));

    // list keep continue here


    foreach (string key in actionMap.Keys)
    {
        if (key == operant)
        {
            actionMap[key]();
        }

    }
}

private void AddToken()
{
}

private void Divide()
{
}

private void LessThanOrEqual()
{
}

// .. and so on

【讨论】:

    【解决方案2】:

    您正在尝试在 switch 语句 ('&lt;=') 中使用字符串(种类)。

    我会使用从字符串到“做某事”的函数的映射。我发现试图强制使用开关会导致比它解决的问题更多的问题。

    【讨论】:

      猜你喜欢
      • 2019-05-08
      • 2015-11-28
      • 1970-01-01
      • 1970-01-01
      • 2017-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多