简体   繁体   English

检查多个类似条件时,是否有办法使if语句更短且更好看? (C#)

[英]Is there a way to make if statement shorter and better looking when checking for multiple similar conditions? (C#)

(not sure if title explains the matter well enough) (不确定标题是否足以说明问题)

I have this piece of code: 我有这段代码:

string input = "5";
   if (input == ""  ||
       input == "1" ||
       input == "2" ||
       input == "3" ||
       input == "4" ||
       input == "_" ||
       input == "6" ||
       input == "7" ||
       input == "8")
     {/* ... */}
   else
     {/* ... */}

How can I make it look better? 如何使它看起来更好? Is there some way to remove repeating input s? 有什么方法可以删除重复的input s吗?

upd : switch will probably make it even worse, because in my case I'm going to check for many conditions, most of which will run very limited number of methods. upd :switch可能会使情况变得更糟,因为在我的情况下,我将检查许多条件,其中大多数将运行非常有限的方法。

Yes, you can write an extension method like this one: 是的,您可以编写这样的扩展方法:

    public static bool In<T>(this T value, params T[] list)
    {
        return list.Contains(value);
    }

And use it as follows: 并按如下所示使用它:

if (input.In("", "1", "2", ...))
...

Well, you can use a switch in the general case (although that experience is much better in VB.NET) but if they're all going to be one character or less, you can use a string: 好吧,您可以在一般情况下使用switch (尽管在VB.NET中这种体验要好得多),但是如果它们都变成一个字符或更少,则可以使用字符串:

if("1234_678".Contains(input)) {
    // ...
}

Wrap the conditional expression in a function and code becomes easier to read. 将条件表达式包装在函数中,代码变得更易于阅读。 The actual expression isn't any simpler but the code is a bit easier to read. 实际的表达并不简单,但是代码更易于阅读。

if (IsSomething(input))
{
 /* do stuff */
}

Maybe you could try using a switch. 也许您可以尝试使用开关。 Its probably more presentable. 它可能更像样。 This would be more appropriate for individual tests if that is what you want. 如果您想要的话,这将更适合于单个测试。

More information can be found here: http://msdn.microsoft.com/en-us/library/06tc147t%28v=vs.71%29.aspx 可以在这里找到更多信息: http : //msdn.microsoft.com/zh-cn/library/06tc147t%28v=vs.71%29.aspx

    switch(input){
      case "1":
      // Do something
      break;
      case "2":
      // Do something else
      break;
      case "_":
      // Do something else
      break;
      default:
      // Otherwise do this
      break;
    }

Or you could do: 或者您可以这样做:

List<string> list = new List<string>{"","1","2","3","4","5","6","7","8"};

            if (list.Contains(input))
            {
                Console.WriteLine("found");
            }

This will be an option to solve this problem: 这将是解决此问题的一种选择:

  string input = "5";
  List<string> Values = new List<string>{ "1", "2","3","4", "5" };
  if(Values .Contains(input))
    {
         //Your Action
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM