本文介绍了将运算符存储在变量中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
是否可以将运算符存储在变量中?我想做这样的事情(伪代码):
Is there a way to store an operator inside a variable? I want to do something like this (pseudo code):
void MyLoop(int start, int finish, operator op)
{
for(var i = start; i < finish; op)
{
//do stuff with i
}
}
然后我可以像这样调用此方法:
I could then call this method like so:
MyLoop(15, 45, ++);
MyLoop(60, 10, --);
C#中是否存在类似的东西?
Does something like this exist in C#?
推荐答案
我想是这样的.您无需定义运算符,而可以定义一个函数(lambda)来为您完成更改.
I suppose something like this. You do not define the operator, but a function (lambda) which does the change for you.
void MyLoop(int start, int finish, Func<int, int> op)
{
for(var i = start; i < finish; i = op(i))
{
//do stuff with i
}
}
然后我可以像这样调用此方法:
I could then call this method like so:
MyLoop(15, 45, x => x+1);
MyLoop(60, 10, x => x-1);
这篇关于将运算符存储在变量中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!