简体   繁体   English

将equals而不是equals传递给函数

[英]Passing equals and not equals into a function

I have two sections of code A and B that are identical to each other, except that A has this 我有两段代码A和B彼此相同,除了A有这个

if(x == y)

and B has this 和B有这个

if(x != y)

where x and y are integers. 其中x和y是整数。

I want to reduce replication of code and so wanted to put this code in a separate method. 我想减少代码的复制,因此希望将此代码放在一个单独的方法中。 The question is how do I pass the == and != operators into such a method and execute it? 问题是如何将==!=运算符传递给这样的方法并执行它?

Like xor it with a bool? 喜欢xor它与bool?

bool negate = true;
...
if ((x == y) ^ negate)
  ...

In case of integer equation and inequity it can solve your problems easily. 在整数方程和不等式的情况下,它可以轻松解决您的问题。

You can pass a Func<int, int, bool> 您可以传递Func<int, int, bool>

private void MyMethod(Func<int, int, bool> checker)
{
    if(checker(3, 4))
    {
         // Do Something.
    }
}

Maybe do like this: 也许这样做:

void TheMethod(Func<int, int, bool> criterion)
{
  ...

  if (criterion(x, y))

  ...
}

then call with TheMethod((x, y) => x == y); 然后调用TheMethod((x, y) => x == y); or TheMethod((x, y) => x != y); TheMethod((x, y) => x != y); .

You want to use a boolean function that acceps a flag for evaluating equality or inequality: 您想使用一个布尔函数来接受一个标志来评估相等或不等式:

bool Eval(bool enforceEquality, T x, T y)
{
   if(enforceEqality)
      return x == y
   else 
      return x != y
}

The name Eval could use some work, but this way you pass the flag in from outside & use it to determine which evaluation returns true. 名称Eval可以使用一些工作,但这样您就可以从外部传递标记并使用它来确定哪个评估返回true。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM