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

use*_*145 1 c# math variables

我知道这是一个奇怪的问题,但这里有一段代码可以更好地解释我想要做什么。

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.
Run Code Online (Sandbox Code Playgroud)

但由于某种原因,控制台读出了 45...很奇怪吧?那么,如果您明白我想要做什么,您能解释一下并告诉我如何做吗?

clc*_*cto 5

您可以使用委托来实现此目的:

 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
Run Code Online (Sandbox Code Playgroud)

另外,您可以使用 lambda 代替命名方法:

 myOp = (a,b) => a + b;
Run Code Online (Sandbox Code Playgroud)