是否可以在变量中存储数学运算(+)并调用该变量,就像您直接使用该运算本身一样 [英] Is it possible to store a math operation (+) in a variable and call on that variable as if you were directly using the operation itself
本文介绍了是否可以在变量中存储数学运算(+)并调用该变量,就像您直接使用该运算本身一样的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我知道这是一个很奇怪的问题,但是这里有一段代码可以更好地解释我要做什么.
I know this is a weird question but here is a chunk of code to better explain what I am trying to do.
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 ...很奇怪,对吗?因此,如果您了解我的工作意图,您可以解释一下并向我展示如何做吗?
But for some reason the console reads out 45... Weird right? So if you understand what I am trying to do can you explain and show me how?
推荐答案
您可以为此使用委托:
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
此外,您可以使用lambda代替命名方法:
Also, you could use lambdas instead of named methods:
myOp = (a,b) => a + b;
这篇关于是否可以在变量中存储数学运算(+)并调用该变量,就像您直接使用该运算本身一样的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文