Делегаты си шарп это

Using Delegates (C# Programming Guide)

A delegate is a type that safely encapsulates a method, similar to a function pointer in C and C++. Unlike C function pointers, delegates are object-oriented, type safe, and secure. The type of a delegate is defined by the name of the delegate. The following example declares a delegate named Del that can encapsulate a method that takes a string as an argument and returns void:

public delegate void Callback(string message); 

A delegate object is normally constructed by providing the name of the method the delegate will wrap, or with a lambda expression. Once a delegate is instantiated, a method call made to the delegate will be passed by the delegate to that method. The parameters passed to the delegate by the caller are passed to the method, and the return value, if any, from the method is returned to the caller by the delegate. This is known as invoking the delegate. An instantiated delegate can be invoked as if it were the wrapped method itself. For example:

// Create a method for a delegate. public static void DelegateMethod(string message)
// Instantiate the delegate. Callback handler = DelegateMethod; // Call the delegate. handler("Hello World"); 

Delegate types are derived from the Delegate class in .NET. Delegate types are sealed—they cannot be derived from— and it is not possible to derive custom classes from Delegate. Because the instantiated delegate is an object, it can be passed as an argument, or assigned to a property. This allows a method to accept a delegate as a parameter, and call the delegate at some later time. This is known as an asynchronous callback, and is a common method of notifying a caller when a long process has completed. When a delegate is used in this fashion, the code using the delegate does not need any knowledge of the implementation of the method being used. The functionality is similar to the encapsulation interfaces provide.

Another common use of callbacks is defining a custom comparison method and passing that delegate to a sort method. It allows the caller’s code to become part of the sort algorithm. The following example method uses the Del type as a parameter:

public static void MethodWithCallback(int param1, int param2, Callback callback)

You can then pass the delegate created above to that method:

MethodWithCallback(1, 2, handler); 

and receive the following output to the console:

Using the delegate as an abstraction, MethodWithCallback does not need to call the console directly—it does not have to be designed with a console in mind. What MethodWithCallback does is simply prepare a string and pass the string to another method. This is especially powerful since a delegated method can use any number of parameters.

When a delegate is constructed to wrap an instance method, the delegate references both the instance and the method. A delegate has no knowledge of the instance type aside from the method it wraps, so a delegate can refer to any type of object as long as there is a method on that object that matches the delegate signature. When a delegate is constructed to wrap a static method, it only references the method. Consider the following declarations:

public class MethodClass < public void Method1(string message) < >public void Method2(string message) < >> 

Along with the static DelegateMethod shown previously, we now have three methods that can be wrapped by a Del instance.

A delegate can call more than one method when invoked. This is referred to as multicasting. To add an extra method to the delegate’s list of methods—the invocation list—simply requires adding two delegates using the addition or addition assignment operators (‘+’ or ‘+=’). For example:

var obj = new MethodClass(); Callback d1 = obj.Method1; Callback d2 = obj.Method2; Callback d3 = DelegateMethod; //Both types of assignment are valid. Callback allMethodsDelegate = d1 + d2; allMethodsDelegate += d3; 

At this point allMethodsDelegate contains three methods in its invocation list— Method1 , Method2 , and DelegateMethod . The original three delegates, d1 , d2 , and d3 , remain unchanged. When allMethodsDelegate is invoked, all three methods are called in order. If the delegate uses reference parameters, the reference is passed sequentially to each of the three methods in turn, and any changes by one method are visible to the next method. When any of the methods throws an exception that is not caught within the method, that exception is passed to the caller of the delegate and no subsequent methods in the invocation list are called. If the delegate has a return value and/or out parameters, it returns the return value and parameters of the last method invoked. To remove a method from the invocation list, use the subtraction or subtraction assignment operators ( — or -= ). For example:

//remove Method1 allMethodsDelegate -= d1; // copy AllMethodsDelegate while removing d2 Callback oneMethodDelegate = allMethodsDelegate - d2; 

Because delegate types are derived from System.Delegate , the methods and properties defined by that class can be called on the delegate. For example, to find the number of methods in a delegate’s invocation list, you may write:

int invocationCount = d1.GetInvocationList().GetLength(0); 

Delegates with more than one method in their invocation list derive from MulticastDelegate, which is a subclass of System.Delegate . The above code works in either case because both classes support GetInvocationList .

Читайте также:  Get method in php curl

Multicast delegates are used extensively in event handling. Event source objects send event notifications to recipient objects that have registered to receive that event. To register for an event, the recipient creates a method designed to handle the event, then creates a delegate for that method and passes the delegate to the event source. The source calls the delegate when the event occurs. The delegate then calls the event handling method on the recipient, delivering the event data. The delegate type for a given event is defined by the event source. For more, see Events.

Comparing delegates of two different types assigned at compile-time will result in a compilation error. If the delegate instances are statically of the type System.Delegate , then the comparison is allowed, but will return false at run time. For example:

delegate void Callback1(); delegate void Callback2(); static void method(Callback1 d, Callback2 e, System.Delegate f) < // Compile-time error. //Console.WriteLine(d == e); // OK at compile-time. False if the run-time type of f // is not the same as that of d. Console.WriteLine(d == f); >

See also

Источник

Использование делегатов (Руководство по программированию на C#)

Делегат — это тип, который безопасно инкапсулирует метод, схожий с указателем функции в C и C++. В отличие от указателей функций в C делегаты объектно-ориентированы, типобезопасны и безопасны. Тип делегата задается его именем. В следующем примере объявляется делегат с именем Del , который может инкапсулировать метод, использующий в качестве аргумента значение string и возвращающий значение void:

public delegate void Callback(string message); 

Объект делегата обычно создается путем предоставления имени метода, для которого делегат будет служить оболочкой, или с помощью лямбда-выражения. После создания экземпляра делегата вызов метода, выполненный в делегате передается делегатом в этот метод. Параметры, передаваемые делегату вызывающим объектом, передаются в метод, а возвращаемое методом значение (при его наличии) возвращается делегатом в вызывающий объект. Эта процедура называется вызовом делегата. Делегат, для которого создан экземпляр, можно вызвать, как если бы это был метод, для которого создается оболочка. Пример:

// Create a method for a delegate. public static void DelegateMethod(string message)
// Instantiate the delegate. Callback handler = DelegateMethod; // Call the delegate. handler("Hello World"); 

Типы делегатов являются производными от класса Delegate в .NET. Типы делегатов являются запечатанными — от них нельзя наследовать, а от Delegate нельзя создавать производные пользовательские классы. Так как экземпляр делегата является объектом , его можно передать в качестве аргумента или назначить свойству. Это позволяет методу принимать делегат в качестве параметра и вызывать делегат в дальнейшем. Эта процедура называется асинхронным обратным вызовом и обычно используется для уведомления вызывающего объекта о завершении длительной операции. Когда делегат используется таким образом, коду, использующему делегат, не требуются сведения о реализации используемого метода. Данные функциональные возможности аналогичны возможностям, предоставляемым интерфейсами инкапсуляции.

Читайте также:  DOM интерфейс

Обратный вызов также часто используется для задания настраиваемого метода сравнения и передачи этого делегата в метод сортировки. Это позволяет сделать коду вызывающего объекта частью алгоритма сортировки. В следующем примере метод использует тип Del тип в качестве параметра.

public static void MethodWithCallback(int param1, int param2, Callback callback)

Затем в данный метод можно передать созданный ранее делегат:

MethodWithCallback(1, 2, handler); 

и получить следующие выходные данные в окне консоли:

При использовании делегата в качестве абстракции методу MethodWithCallback не нужно выполнять непосредственный вызов консоли, то есть его можно создавать без учета консоли. Метод MethodWithCallback просто подготавливает строку и передает ее в другой метод. Это очень удобно, так как делегируемый метод может использовать любое количество параметров.

Если делегат создан в качестве оболочки для метода экземпляра, этот делегат ссылается и на экземпляр, и на метод. Делегат не имеет сведений о типе экземпляра, кроме полученных из метода, для которого он является оболочкой, поэтому делегат может ссылаться на любой тип объекта, если для этого объекта есть метод, соответствующий сигнатуре делегата. Если делегат создан в качестве оболочки для статического метода, он ссылается только на метод. Рассмотрим следующее объявление:

public class MethodClass < public void Method1(string message) < >public void Method2(string message) < >> 

Вместе с рассмотренным ранее статическим методом DelegateMethod есть три метода, для которых можно создать оболочку с помощью экземпляра Del .

При вызове делегат может вызывать сразу несколько методов. Это называется многоадресностью. Чтобы добавить в список методов делегата (список вызова) дополнительный метод, необходимо просто добавить два делегата с помощью оператора сложения или назначения сложения («+» или «+ lang-csharp» name=»csProgGuideDelegates#27″>var obj = new MethodClass(); Callback d1 = obj.Method1; Callback d2 = obj.Method2; Callback d3 = DelegateMethod; //Both types of assignment are valid. Callback allMethodsDelegate = d1 + d2; allMethodsDelegate += d3;

Читайте также:  Text underline position css

На данном этапе список вызова делегата allMethodsDelegate содержит три метода — Method1 , Method2 и DelegateMethod . Три исходных делегата d1 , d2 и d3 остаются без изменений. При вызове allMethodsDelegate все три метода вызываются по порядку. Если делегат использует параметры, передаваемые по ссылке, эта ссылка передается после каждого из трех методов, а все изменения одного из методов становятся видны в следующем методе. Если любой из методов вызывает неперехваченное исключение, это исключение передается в вызывающий делегат объект, а последующие методы в списке вызова не вызываются. Если делегат имеет возвращаемое значение и (или) выходные параметры, он возвращает возвращаемое значение и параметры последнего вызванного метода. Чтобы удалить метод из списка вызовов, используйте вычитание или операторы присваивания вычитания ( — или -= ). Пример:

//remove Method1 allMethodsDelegate -= d1; // copy AllMethodsDelegate while removing d2 Callback oneMethodDelegate = allMethodsDelegate - d2; 

Поскольку типы делегата являются производными от System.Delegate , в делегате можно вызывать методы и свойства, определенные этим классом. Например, чтобы определить число методов в списке вызова делегата, можно использовать код:

int invocationCount = d1.GetInvocationList().GetLength(0); 

Делегаты, в списке вызова которых находятся несколько методов, является производным от MulticastDelegate, являющегося подклассом класса System.Delegate . Приведенный выше код работает в любом из случаев, так как оба класса поддерживают GetInvocationList .

Групповые делегаты часто используются при обработке событий. Объекты источников событий отправляют уведомления объектам получателей, зарегистрированным для получения данного события. Чтобы зарегистрироваться для получения события, объект получателя создает метод, предназначенный для обработки этого события, затем создает делегат для этого метода и передает его в источник события. Когда происходит событие, источник вызывает делегат. После этого делегат вызывает в объекте получателя обработки события, предоставив ему данные события. Тип делегата для данного события задается источником события. Дополнительные сведения см. в разделе События.

Назначение сравнения делегатов двух различных типов во время компиляции вызовет ошибку компиляции. Если экземпляры делегата статически относятся к типу System.Delegate , сравнение допустимо, но во время выполнения будет возвращено значение false. Пример:

delegate void Callback1(); delegate void Callback2(); static void method(Callback1 d, Callback2 e, System.Delegate f) < // Compile-time error. //Console.WriteLine(d == e); // OK at compile-time. False if the run-time type of f // is not the same as that of d. Console.WriteLine(d == f); >

См. также раздел

Источник

Оцените статью