Skip to main content
 首页 » 编程设计

c#之函数输入参数的符号参数

2024年02月13日11arxive

我正在编写 C# 代码,我想在函数中传递一个参数,这将是这些符号之一 <、>、==、!=

private Image ThresholdImageFilter(image, symbol, threshold) 
{ 
 
for (int i = 1; i < 512; i++) 
{ 
   for (int j = 1; j < 512; j++) 
    { 
       for (int j = 1; j < 512; j++) 
         { 
          if pixel symbol threshold; 
               { 
                     pixel = 1; 
               } 
          else 
               { 
                     pixel = 0; 
               } 
         } 
    } 
  } 
 
} 

我想多次调用一个函数,但使用不同的符号,如下所示:

AImage = ThresholdImageFilter(image > threshold); 
BImage = ThresholdImageFilter(image < threshold); 
CImage = ThresholdImageFilter(image <= threshold); 
DImage = ThresholdImageFilter(image >= threshold); 

我正在寻找这样的东西:

private Image Filter(Bitmap image, symbolArgument symbol, int threshold) 
{ 
     ... 
} 

最后像这样调用函数:

BinaryImage = Filter(imageB, >, threshold); 

有办法吗?如果是这样,请建议如何传递 >= 或 <=(由 2 个符号组成)。

请您参考如下方法:

让过滤器接受一个接受两个参数并返回一个 bool 值的委托(delegate)。然后,您可以使用给定的运算符将 lambda 传递给该参数:

public SomeResult Filter(Func<ArgumentType, ArgumentType, bool> predicate) 
{ 
    if(predicate(operand1, operand2)) 
        DoSomething(); 
} 

然后你会这样调用它:

var result = Filter((a,b)=> a > b);