你可以写一个扩展。我以前写过一次,用于制作类似的代码
if(someObject.stringPropertyX.Equals("abc") || someObject.stringPropertyX.Equals("def") || ....){
//do something
...
}else{
//do something other...
....
}
更易读的扩展 st one 能够写
if(someObject.stringPropertyX.In("abc", "def",...,"xyz"){
//do something
...
}else{
//do something other...
....
}
这是代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Some.Namespace.Extenders
{
public static class StringExtender
{
/// <summary>
/// Evaluates whether the String is contained in AT LEAST one of the passed values (i.e. similar to the "in" SQL clause)
/// </summary>
/// <param name="thisString"></param>
/// <param name="values">list of strings used for comparison</param>
/// <returns><c>true</c> if the string is contained in AT LEAST one of the passed values</returns>
public static bool In(this String thisString, params string[] values)
{
foreach (string val in values)
{
if (thisString.Equals(val, StringComparison.InvariantCultureIgnoreCase))
return true;
}
return false; //no occurence found
}
}
}
这是我当时特定的需求,但您可以对其进行调整和修改以匹配更多不同的类型。