private delegate int Operate(int x, int y);
Operate usedOperator;
int Add(int x, int y)
{
return x + y;
}
usedOperator.ToString()应返回“+”“ - ”或委托当前包含的任何方法。这有可能吗?
修改 委托方法的替代方案也可以。我基本上正在编写一个程序,用随机数和运算符向用户询问一些数学问题。
答案 0 :(得分:3)
你不能覆盖委托的成员,但你可以用表达式实现你想要的东西:
Expression<Func<int, int, int>> expr = (a, b) => a + b;
Console.WriteLine(expr.Body.ToString()); // prints "(a + b)"
答案 1 :(得分:1)
为什么不使用继承&amp;多态性。
创建一个抽象类MathOperation并创建多个实现MathOperation的类,例如AddOperation,SubtractOperation等。您可以在这些类中覆盖ToString()
在您的代码中,您应该:
MathOperation operation = new AddOperation(x, y); // or new MultiplyOperation(x, y);
operation.Perform(); // This will perform addition
operation.ToString(); // This will print "+"