在c#中,是否可以传递或返回类似类型的运算符
我有一个excel exporter类,它必须从第三方获取过滤信息,并使用这些信息过滤数据。过滤信息以字符串形式出现,如“equals”、“greatherthan”等。生成可将这些过滤类型转换为c#代码的可重用代码的最佳方法是什么 我在想,把它们转换成操作符并返回它可能会更好。但我不知道这是否可能,甚至是一个好主意。你觉得怎么样?试试这个:在c#中,是否可以传递或返回类似类型的运算符,c#,C#,我有一个excel exporter类,它必须从第三方获取过滤信息,并使用这些信息过滤数据。过滤信息以字符串形式出现,如“equals”、“greatherthan”等。生成可将这些过滤类型转换为c#代码的可重用代码的最佳方法是什么 我在想,把它们转换成操作符并返回它可能会更好。但我不知道这是否可能,甚至是一个好主意。你觉得怎么样?试试这个: public class ExcelFiltersManager { public static class ExcelFilters
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;
}
}
看见感兴趣的可能是中介模式或代理模式。我认为是策略模式。您描述的运算符(>,!=etc)只是接受两个相同类型的参数并返回bool的函数。因此,您可以将它们存储为Func委托(其中T是参数的类型)。您是否可以在传入字符串中搜索这些字符,并使用switch语句来调用由找到的字符决定的函数?嗯。这很有趣,我不知道内部运算符有字符串名称。让我看看其他一些建议,但这看起来很有希望。谢谢
decimal value1 = 5;
decimal value2 = 10;
bool result = GetOperatorBooleanResult(ExcelFilters.GreaterThen, value1, value2);