是否可以将数学运算(+)存储在变量中,并像直接使用运算本身一样调用该变量

本文关键字:变量 运算 调用 一样 是否 存储 | 更新日期: 2023-09-27 18:20:46

我知道这是一个奇怪的问题,但这里有一大块代码可以更好地解释我要做的事情。

char plus = '+'; //Creating a variable assigning it to the + value.
//Instead of using + we use the variable plus and expect the same outcome.     
Console.WriteLine(1 + plus + 1); 
Console.ReadLine(); //Read the line.

但出于某种原因,控制台显示45…奇怪吧?所以,如果你明白我想做什么,你能解释并告诉我怎么做吗?

是否可以将数学运算(+)存储在变量中,并像直接使用运算本身一样调用该变量

您可以将委托用于此目的:

 void int Add( int a, int b ) { return a + b; }
 void int Subtract( int a, int b ) { return a - b; }

 delegate int Operation( int a, int b );
 Operation myOp = Add;
 Console.WriteLine( myOp( 1, 1 ) ); // 2
 myOp = Subtract;
 Console.WriteLine( myOp( 1, 1 ) ); // 0

此外,您可以使用lambdas而不是命名方法:

 myOp = (a,b) => a + b;

在使用.Net 3.5或更高版本的情况下,您可以使用Func<>和lambdas(而不需要显式使用委托):

Func<int, int, int> plus = (a, b) => a + b; //Creating a variable assigning it to the + value.
//Instead of using + we use the variable plus and expect the same outcome.     
Console.WriteLine(plus(1, 1)); 
Console.ReadLine(); //Read the line.