Began to study the delegates and their use without events. I looked through many different articles, books and examples. And in principle, I understood the essence of the delegates. But I didn’t understand a couple of things: And what is the real advantage, so to speak of the merits, of using delegates? And are there any downsides for delegates as such?
Closed due to the fact that it is necessary to reformulate the question so that it was possible to give an objectively correct answer to the participants of Saidolim , Abyx , Grundy , user194374, Mike Jan 2, 16 at 19:51 .
The question gives rise to endless debates and discussions based not on knowledge, but on opinions. To get an answer, rephrase your question so that it can be given an unambiguously correct answer, or delete the question altogether. If the question can be reformulated according to the rules set out in the certificate , edit it .
- Comments are not intended for extended discussion; conversation moved to chat . - Nick Volynkin ♦
3 answers
Events are just a special case of the use of delegates. The delegate itself is essentially a reference to an arbitrary method with a strictly defined signature. Talking about the advantages and disadvantages can only be compared with implementations in other languages. Subtleties of use, of course, are and are described in detail by Richter himself. For a more detailed answer, a more specific question is needed.
Delegates allow you to call methods that do not know their name.
For example, there are two classes
class B { public void M(int i) { Console.WriteLine("BM:" + i); } } class A { public void M1(int i) { Console.WriteLine("A.M1:" + i); } static public void M2(int i) { Console.WriteLine("A.M2:" + i); } } You need to define a method that will call methods BM, A.M1, A.M2, or any other method with a similar signature.
To do this, we define a delegate
delegate void TestMethod(int i); In the definition of a delegate, the return type and the types of parameters are similar to those defined in the methods BM, A.M1, A.M2
Define a method for invoking a delegate:
void Test(TestMethod m) { m(1); } it is possible to pass 'links' to different methods, including static, from different classes.
var a = new A(); Test(a.M1); Test(A.M2); var b = new B(); Test(bM); result
A.M1:1 A.M2:1 BM:1 On the basis of the delegates are determined events.
For example, an event can be defined as:
event TestMethod Tests; this also creates a heir of the MulticastDelegate class.
Console.WriteLine(Tests.GetType().BaseType.Name); // MulticastDelegate var a = new A(); var b = new B(); // добавим обработчики в событие Tests Tests += a.M1; Tests += A.M2; Tests += bM; /* другой способ добавления обработчиков в событие Tests = (TestMethod)Delegate.Combine(Tests, new TestMethod(a.M1)); Tests = (TestMethod)Delegate.Combine(Tests, new TestMethod(A.M2)); Tests = (TestMethod)Delegate.Combine(Tests, new TestMethod(bM)); */ // посылаем событие, при этом вызываются обработчики Tests(1); result
A.M1:1 A.M2:1 BM:1 Why do I need to specify the event?
class C { public TestMethod Tests1; public event TestMethod Tests2; } var c = new C(); var i1 = c.Tests1.GetInvocationList(); var i2 = c.Tests2. // error CS0070, т.к. нет доступа к свойствам и методам Tests2 can only be called from the methods / properties of class C. To do this, add a method to the class, for example:
public void Run() { var e = this.Tests2; if(e != null) e(1); } - onethose who put the cons, write what's wrong? - Stack
- you answered the wrong question that was asked - Pavel Mayorov
- @PavelMayorov "you answered the wrong question that was asked" - the question says "what is the actual advantage". I answer and show the main purpose = advantage. Do you know another? Write what. - Stack
- oneappointment is not an advantage. The advantage can only be in relation to alternatives. - Pavel Mayorov
- onethat's it, the author of the question needs a comparison of delegates and events, no matter how stupid it may sound, and not a simple story about them - Pavel Mayorov
Events are a mechanism based on delegates. Syntax for implementing default events
public class MyClass { public event EventHandler SomeEvent; } unfolds into something like
public class MyClass { // виден изнутри класса как SomeEvent, вызываем private EventHandler SomeEventHandlers; // виден снаружи класса как SomeEvent, предоставляет синтаксис += и -= public event EventHandler SomeEvent { add { SomeEventHandlers += value; } remove { SomeEventHandlers -= value; } } } those. the question of the “advantages” and “minuses” is in itself incorrect. If you need event semantics
- the very fact of having a "logical" event
- one point full subscription
- single instance creating event
- the validity of the terms "subscribe" and "unsubscribe" in a particular situation
then use the event.
If the semantics of the event is not applicable (for example, this is somehow a test static callback) - use the delegate.
Delegates in a "pure" form are widely used in a standard framework. For example, the entire LINQ to Objects — manipulation of collections — is built on passing delegates of type Func<T> :
int[] someArray = ...; int[] filtered = someArray.Where(i => i % 2 == 0).ToArray(); In this example, i => i % 2 == 0 is the declaration of an anonymous function (via a lambda expression), and the creation based on its delegate. Those. This is an analogue of the code:
private static bool Filter(int i) { return i ℅ 2 == 0; } Func<int, bool> filterDelegate = Filter; int[] filtered = someArray.Where(filterDelegate).ToArray(); - "anonymous delegate declaration" - they say that anonymous delegates do not exist - here . although msdn has an example of anonymous delegates , but apparently this is one of the many inaccuracies of msdn. - Stack
- @Stack is an intentional admission, to facilitate understanding. In expanded form, I added a specific delegate variable to show that all this works on the basis of delegates, and not at the expense of magic. Consider what I called "anonymous" exactly her :) - PashaPash ♦
- @Stack reformed, now everything is canonical. - PashaPash ♦