Delegates allow you to create a variable that “points” to a method. You can use this variable
at any time to invoke the method. Delegates help you write flexible code that can be
reused in many situations. They’re also the basis for events The first step when using a delegate is to define its signature. A delegate variable can point only to a method that matches its specific signature. In other words, it must have the same return type and the same parameter types. For example, if you have a method that accepts a single string parameter and another method that accepts two string parameters,
you’ll need to use a separate delegate type for each method. To consider how this works in practice, assume your program has the following
function:
private string TranslateEnglishToFrench(string lang)
{
//statments;
}
This function returns a string and accepts a single string argument. With those two
details in mind, you can define a delegate that matches this signature. Here’s how you
would do it: private delegate string StringFunction(string in);
Notice that the name you choose for the parameters and the name of the delegate
don’t matter. The only requirement is that the data types for the return value and parameters
match exactly. Once you’ve defined a type of delegate, you can create and assign a delegate variable at any
time. Using the StringFunction delegate type, you could create a delegate variable like this:
StringFunction functionReference;
Once you have a delegate variable, the fun begins. Using your delegate variable,
you can point to any method that has the matching signature. In this example, the
StringFunction delegate type requires one string parameter and returns a string.
Thus, you can use the functionReference variable to store a reference to the
TranslateEnglishToFrench() function you saw earlier. Here’s how to do it:
FunctionReference=TranslateEnglishToFrench;

0 comments:
Post a Comment