DenkzeitWiki

Suchen:

Aktuelle Änderungen Printable View Änderungen Bearbeiten

VisualStudio > KnotTying > ModPython > ComPreVal > CodeSwarm > WordPress > MapReduce > PyChecker > JavaBeans > PingBacks > PingBack > Branching > PythonXML > WikiWords > WikiWord > Junctions > DelegatesClear Trail
Main /

Delegates

CSharp
Functor

Closures
LambdaExpressions
Something like function-pointers in C++. But type-safe.

Think of a delegate as an interface declaring exactly one method. An instantiation of a delegate is similar to an anonymous inner class that implements the interface through a one-line call to a single method (static or instance) with a compatible signature.


 public class Class {
    public void display(String s) { Console.WriteLine(s); }
 }

 public delegate void doShow(String s);

 doShow item = new doShow(new Class().display);
Note that the display-method is given as an object (not an actual call) to the delegate doShow!
Note also that the signature of the delegate and the wrapped method are identical: (String) in the example.

Delegates can be simulated in Java by means of reflection: Give Object and name of function to some administring object (delegator).

Delegates handle problems which would be solved with function pointers in C++, and interfaces in Java. [1]



You can create a delegate to any (reference or value type) object which has a method of the right signature.

  • Interfaces are faster. Should be used when possible to put them into the class-hierarchy.
  • Delegates allow adaption of methods with different name but same signature. Feels a bit like DuckTyping for methods...


Events With Delegates

The 'event' keyword hides all the delegate's methods apart from += and -= to classes other than the class it is declared in. [2]



C# allows you to create a multicast delegate instance by using the 'event' keyword [3]



Discussion


Q&A

What's the difference between delegates and methods as objects?

I can delegate a method-invokation (of a method that is bound to an instance) in Python:
  >>> class test(object):
 ...     def method(self, o):
 ...             self.o = o
 ...
 >>> test.method
 <unbound method test.method>
 >>> test().method
 <bound method test.method of <__main__.test object at 0x008D1870>>
 >>> t = test()
 >>> t.method
 <bound method test.method of <__main__.test object at 0x008D1B70>>
 >>> t.method(3)
 >>> t.o
 3
 >>> delegate = t.method
 >>> delegate(6)
 >>> t.o
 6

Edit - BackLinks - Tags - Page Hist - Print - Changes - Home - Orphans - Help

Zuletzt geändert am 21.11.2010 19:53 Uhr und seit 7. April 2005 1715 aufgerufen.