使用string类型中的参数作为逻辑运算符(通过C#) [英] Use of parameter in type of string as logical operator (by C#)

查看:257
本文介绍了使用string类型中的参数作为逻辑运算符(通过C#)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Hi
我向函数发送3个参数。 (int d1,int d2,string operator)

例如:(12,14,>)。

现在在函数中我想要一个条件。

条件:

如果(d1运算符d2)//不正确

如果(d1 +运算符+ d2)//不正确

if(convert.toBolean(d1 + operator + d2))//不正确

如何写条件?



非常感谢

Hi I send 3 parameter to a function. (int d1, int d2, string operator)
For example : (12, 14, ">").
Now in function I wants to have a condition.
Condition :
if (d1 operator d2) // is incorrect
if (d1 + operator + d2) // is incorrect
if (convert.toBolean (d1+ operator + d2)) // is incorrect
How can I write condition ?

Thanks very much

推荐答案

字符表示的运算符?嗯,好吧......



这听起来像是一个非常糟糕的方法。由于某种原因,一个最糟糕的误解困扰着初学者:尝试使用表示数据的字符串而不是数据本身。在这种情况下,您尝试使用字符串而不是代码。更糟糕的是?我不知道,无论如何,非常糟糕...



你至少明白:如果你拼错了操作员字符,编译器就不会警告你有没有错误?



您可以使用非常简单和高效的方法。 传递实施操作员的委托实例而不是操作员(实际上不是这样)。



你得到了吗?这个想法?让我们看看:

Operator denoted by a character? Well, well…

This sounds like a really bad approach. By some reason, one worst misconception haunts the beginners: an attempt to use strings representing data, instead of data itself. And in this case, you are trying to use string instead of code. Is it even worse? I don''t know, anyway, very bad…

Do you at least understand: should you misspell the "operator" character, the compiler won''t warn you on the bug?

You can use a very simple and productive approach instead. Instead of "operator" (which is actually not, in your case), pass a delegate instance implementing the operator.

Are you getting the idea? Let''s see:
static bool MyMethod(int left, int right, System.Func<int, int, bool> userPredicate) {
    // ...
    bool result = userPredicate(left, right);
    // ...
    return result;
} // MyMethod





现在,如何在通话中使用它?让我们看看:



Now, how to use it in the call? Let''s see:

static void Test() {
     bool greater = MyMethod(2, 1, (l, r) => l > r);
     bool equal = MyMethod(4, 4, (l, r) => l == r);
} // Test





很简单,不是吗?



-SA

这篇关于使用string类型中的参数作为逻辑运算符(通过C#)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆