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 "+"
精彩评论