// Create a BinaryOp object that
// "points to" SimpleMath.Add().
BinaryOp b = new BinaryOp(SimpleMath.Add);
// Invoke Add() method indirectly using delegate object.
Console.WriteLine("10 + 10 is {0}", b(10, 10));
Console.ReadLine();
}
}
}
Again, notice the format of the BinaryOp delegate, which can point to any method taking two
integers and returning an integer (the actual name of the method pointed to is irrelevant). Here, we
have created a class named SimpleMath, which defines two static methods that (surprise, surprise)
match the pattern defined by the BinaryOp delegate.
When you want to insert the target method to a given delegate, simply pass in the name of the
method to the delegate’s constructor. At this point, you are able to invoke the member pointed to
using a syntax that looks like a direct function invocation:
Do'stlaringiz bilan baham: |