有没有办法将运算符存储在变量中?我想做这样的事情(伪代码):
void MyLoop(int start, int finish, operator op)
{
for(var i = start; i < finish; op)
{
//do stuff with i
}
}
然后我可以像这样调用这个方法:
MyLoop(15, 45, ++);
MyLoop(60, 10, --);
C# 中有这样的东西吗?
最佳答案
我想是这样的。您不定义运算符,而是定义一个函数 (lambda),它会为您进行更改。
void MyLoop(int start, int finish, Func<int, int> op)
{
for(var i = start; i < finish; i = op(i))
{
//do stuff with i
}
}
然后我可以像这样调用这个方法:
MyLoop(15, 45, x => x+1);
MyLoop(60, 10, x => x-1);
关于c# - 将运算符存储在变量中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14255618/