What is the main use of delegate and their main advantages?? we can also use simple methods in place of delegate,then why we use delegate??
2 に答える
There are a lot of great uses of delegates, but one important benefit over a simple method is the ability to close over the environment. So, without delegates or lambdas or some other similar feature, it's impossible to write code like
public delegate int PartiallyApplied(int b);
public static PartiallyApplied CurriedAdd(int a)
{
return delegate (int b)
{
return a + b;
};
}
You may be wondering why closing over the environment is useful. One important use case is LINQ. A simple method that keeps only the elements of a sequence that are within a certain range is
public IEnumerable<int> WithinRange(this IEnumerable<int> seq, int lower, int upper)
{
return select n from seq where n >= lower && n < upper;
}
(As this is demo code, it is missing error checking and other features of production code)
This code desugars to
public IEnumerable<int> WithinRange(this IEnumerable<int> seq, int lower, int upper)
{
return seq.Where(n => n >= lower && n < upper);
}
which uses a lambda that closes over the lower
and upper
local variables. Without delegates or lambdas, it would be impossible to achieve such clear and succinct code for this kind of task.
Delegates are function pointers done right.
You can 'hot swap' functions in and out at run-time. You can pass them to other functions.