if语句具有变量运算符 [英] if statement to have variable operator
本文介绍了if语句具有变量运算符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
假设我有一个循环,可从操作员字段中检索操作员.
例如,返回的变量strOperator是以下值之一:
操作员
--------
=
>
Hi,
Let say I have a loop which retrieves the operators from the operator field.
For example the variable strOperator returned is one of the following values:
Operator
--------
=
>
推荐答案
您将不得不编写一个(非常小的)解释器(或者它可能更像是编译器,在加载时进行映射).像这样的东西:
You will have to write a (very small) interpreter (or it might be more like a compiler, doing the mapping at load time). Something like:
static Dictionary<string, Func<int, int, bool>> map = new Dictionary<string, Func<int, int, bool>>();
static constructor(){
map["="] = (a, b) => a == b;
map["<"] = (a, b) => a < b;
// ... etc
}
void method(){
string comparator = "<";
int a = 5, b = 8;
if(map[comparator](a, b)){
// ...
}
}
这篇关于if语句具有变量运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文