开发者

Overriding delegate.ToString()

 private delegate int Operate(int x, int y);
 Operate usedOperator;

 int Add(int x, int y)
 {
  return x + y;
 }

usedOperator.ToString() should return either "+" "-" or whatever method the delegate currently contains. Is this po开发者_如何转开发ssible somehow?

EDIT: Alternatives to the delegate approach would be fine too. I basically am writing a program that asks the user some math questions with randomized numbers and operators.


You can't override members of a delegate, but you could achieve what you want with expressions:

Expression<Func<int, int, int>> expr = (a, b) => a + b;
Console.WriteLine(expr.Body.ToString()); // prints "(a + b)"


Why not use inheritance & polymorphism.
Create an abstract class MathOperation and create multiple classes that implement MathOperation, e.g. AddOperation, SubtractOperation and so on. You can override ToString() in these classes.
In your code you should have:


MathOperation operation = new AddOperation(x, y); // or new MultiplyOperation(x, y);
operation.Perform(); // This will perform addition
operation.ToString(); // This will print "+"
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜