我有一个excel导出器类,必须从第三方获取过滤信息并使用该信息过滤数据。过滤信息以“equals”,“greatherthan”等字符串形式出现。生成可重用代码的最佳方法是什么,可以将这些过滤类型转换为c#代码。
我认为将它们转换为运算符并返回它可能会很好。但我不知道这是否可能,甚至不是一个好主意。你觉得怎么样?
答案 0 :(得分:0)
试试这个:
public class ExcelFiltersManager
{
public static class ExcelFilters
{
public const string Equal = "equals";
public const string GreaterThen = "greaterthan";
// complete here the other operators.
}
static class Operators
{
// C# compiler converts overloaded operators to functions with name op_XXXX where XXXX is the opration
public const string Equality = "op_Equality";
public const string InEquality = "op_Inequality";
public const string LessThan = "op_LessThan";
public const string GreaterThan = "op_GreaterThan";
public const string LessThanOrEqual = "op_LessThanOrEqual";
public const string GreaterThanOrEqual = "op_GreaterThanOrEqual";
}
public bool GetOperatorBooleanResult<T>(string excelFilter, T value1, T value2)
{
MethodInfo mi = typeof(T).GetMethod(GetOperatorCompileName(excelFilter), BindingFlags.Static | BindingFlags.Public);
return (bool)mi.Invoke(null, new object[] { value1, value2 });
}
private string GetOperatorCompileName(string excelFilter)
{
string operatorCompileName = string.Empty;
switch (excelFilter)
{
case ExcelFilters.Equal:
operatorCompileName = Operators.Equality;
break;
case ExcelFilters.GreaterThen:
operatorCompileName = Operators.GreaterThan;
break;
// continue here the mapping with the rest of operators
}
return operatorCompileName;
}
}
然后在您的代码中,您可以使用以下内容来获取过滤器的结果:
decimal value1 = 5;
decimal value2 = 10;
bool result = GetOperatorBooleanResult(ExcelFilters.GreaterThen, value1, value2);