您可以编写扩展名。我前一次写,是为了使代码像
if(someObject.stringPropertyX.Equals("abc") || someObject.stringPropertyX.Equals("def") || ....){
//do something
...
}else{
//do something other...
....
}
具有扩展性,可读性更高,可以写
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
}
}
}
这是当时针对我的需求的一种,但是您可以对其进行修改和修改以匹配更多不同的类型。