English 中文(简体)
Delegates in C#
原标题:
  • 时间:2009-11-14 18:55:53
  •  标签:
  • c#
  • delegates

I`m having some trouble in understanding how delegates in C# work. I have many code examples, but i still could not grasp it properly.

Can someone explain it to me in "plain english"? Of course! examples of code will help, but i think i need more of a description of how/why it works.

EDIT:

Well, the question is: why does delegates work? What is a "flow chart" of the entire process?

What are the pre-requisites of using delegates?

I hope this makes the question clearer.

最佳回答

One way to think about a delegate is like a reference to a function. For example, say you have a button in a window, and you want something to happen when the button is clicked. You can attach a delegate to the Click event of the button, and whenever the user clicks this button, your function will be executed.

class MyWindow : Window
{
    Button _button;

    public MyWindow()
    {
        _button = new Button();
        // place the button in the window
        _button.Click += MyWindow.ButtonClicked;
    }

    static void ButtonClicked(object sender, RoutedEventArgs e)
    {
        MessageBox.Show("Button Clicked");
    }
}

Notice how I make ButtonClicked a static function - I want to make a point about non-static functions next. Suppose instead that ButtonClicked is a non-static member:

class MyWindow : Window
{
    Button _button;
    int _numClicked = 0;

    public MyWindow()
    {
        this._button = new Button();
        // place the button in the window
        this._button.Click += this.ButtonClicked;
    }

    void ButtonClicked(object sender, RoutedEventArgs e)
    {
        this._numClicked += 1;
        MessageBox.Show("Button Clicked " + this._numClicked + " times");
    }
}

Now the delegate contains both a reference to the function "ButtonClicked" and the instance, "this", which the method is called on. The instance "this" in the MyWindow constructor and "this" in ButtonClicked are the same.

This is a specific case of a concept known as closures which allows "saving" the state - the current object, local variables, etc. - when creating a delegate. In the above example, we used "this" from the constructor in the delegate. We can do more than that:

class MyWindow : Window
{
    Button _button;
    int _numClicked = 0;

    public MyWindow(string localStringParam)
    {
        string localStringVar = "a local variable";
        this._button = new Button();
        // place the button in the window
        this._button.Click += new RoutedEventHandler(
            delegate(object sender, RoutedEventArgs args)
            {
                this._numClicked += 1;
                MessageBox.Show("Param was: " + localStringParam + 
                     " and local var " + localStringVar +
                     " button clicked " + this._numClicked + " times");
            });
    }
}

Here we created an anonymous delegate - a function which is not given an explicit name. The only way to refer to this function is using the RoutedEventHandler delegate object. Furthermore, this function exists in the scope of the MyWindow constructor, so it can access all local parameters, variables, and the member instance "this". It will continue to hold references to the local variables and parameters even after the MyWindow constructor exits.

As a side note, the delegate will also hold a reference to the object instance - "this" - even after all other references to the class a removed. Therefore, to ensure that a class is garbage collected, all delegates to a non-static member method (or delegates created in the scope of one) should be removed.

问题回答

Well, a delegate is a type. The variables of a delegate type can reference, or point to, a function.

This gives you an indirect way to call a method, so methods can be selected at runtime. And thus you can have variables, parameters and properties containing a method. The properties are called events.

Just one more code sample, to be complete:

   delegate void ADelegate();  // the delegate type

   void Foo() { ... }   // a compatible method
   void Bar() { ... }   // a compatible method

   void Main()
   {
      ADelegate funcPtr;  // a delegate variable
   
      if (aCondition)
        funcPtr = Foo;  // note: _not_ Foo(), Foo is not executed here
      else
        funcPtr = Bar;

      funcPtr(); // calls Foo or Bar depending on aCondition
   }

Use of delegate variables is not common. But you can use a delegate parameter to for instance a Sort method to select an ascending or descending sort.

  delegate int Compare(MyClass a, MyClass b);  // the delegate type

  int CompareUp(MyClass a, MyClass b) { ... }   
  int CompareDn(MyClass a, MyClass b) { ... }   

  void Sort(MyClass[] data, Compare comparer) { ... }

And you probably know events, which are (a special kind of) properties based on delegates.

1) First you have to understand why/when you need a delegate, what is the problem that it solve.

In my experience I mainly use them to allow a user to customize an object s behavior.

Immagine a Grid component that allows the developer to customize how each column will be rendered. For example you want to write a of red color value when it s a number under zero.

The developer that create the Grid does not know how the user want to customize the output so it need a mechanism that let the user of the component to inject some logic into the component.

2) Then you have to understand how the delegate works

What is confusing is the strange code you have to write to do so, and the many ways you have to do the same thing.

This is the grid class:

// the grid let the programmer that will use it to customize the output
public class Grid{

    // 1) First I declare only the interface of the delegate
    public delegate String ValueFormatterDelegate(String v);

    // 2) I declare a handler of the implementation of the delegate
    public ValueFormatterDelegate ValueFormatterHandler; 

    // 3) I call the handler inside the Print method
    public void Print(String x){
        Console.WriteLine( ValueFormatterHandler.Invoke(x) );
    }

}

// 1) First I declare only the interface of the delegate public delegate String ValueFormatterDelegate(String v);

Note that is like a normal method but:

  • it has a delegate keyword
  • it don t has a implementation

In this way I say: "the method that will format the output has this interface: it will take a string as input and it will output a string"

It remember to me a definition of a method of an interface.

// 2) I declare a handler of the implementation of the delegate public ValueFormatterDelegate ValueFormatterHandler;

Now I have to create a property of the type of the delegate that will handle te implementation of this method.

// 3) I call the handler inside the Print method public void Print(String x){ Console.WriteLine( ValueFormatterHandler.Invoke(x) ); }

Inside the Print method I can use the handler that will link the real implementation.

ValueFormatterHandler is of type ValueFormatterDelegate and ValueFormatterDelegate is ad delegate and .Invoke is a method of delegate type

This is a program that use my Grid class and is able to personalize it on the fly. The problem here is the many ways you have to do the same thing.

using System;

public class Program{
    public static void Main(){

        var printer = new Printer();

        // METHOD 1 : link to a named method
        // here i link the handler of the delegate to a real method
        // the FormatXXX is a static method defined at the ed of this code
        printer.ValueFormatter = FormatXXX;

        // when i call Print("hello")
        printer.Print("hello"); // XXhelloXX

        // METHOD 2 : anonimous method
        // think at this like a method but without a name
        // FormatYY (String x ){ return "YY"+x+"YY"; };
        //  become
        // delegate (String x ){ return "YY"+x+"YY"; };
        printer.ValueFormatter = delegate (String x ){ return "YY"+x+"YY"; };
        printer.Print("hello"); // YYhelloYY

        // METHOD 3 : anonimous method using lambda
        // as you can note the type of parameter x is inferred from the delegate declaration
        // public delegate String ValueFormatterDelegate(String v);
        printer.ValueFormatter = (x)=>"KK" + x + "KK";

    }

    public static String FormatXXX(String y){
        return "XX"+ y +"XX";
    }

}

Its an inversion principle. Normally, you write code that calls a method and the method you call is known at the time that you write the code. Delegates allow you to anonymously invoke methods. That is you do not know the actual method that is called when the program is running.

It is useful in separating the concerns of different parts of an application. So you can have some code that performs tasks on a data store. You may have other code that processes the data. The processes on the data need not know the structure of the data store and the data store should not be dependant on the uses of the data.

The processing code can be written assuming certain things about the data that are independant of the structure of the data store. That way, we can change the structure of the data store with less worry about affecting the processes on the data.

You can think of delegates as a way to view code as data. If you create a delegate, it is a type. Variables of this type may point to specific methods (that comply with the delegate definition).

That means that you can treat a piece of code as data and for instance pass it to a method. Since delegates point to code (or null), you may also invoke the code that it points to via the variable.

That allows for some very useful patterns. The classic example is how to sort a collection. By allowing the caller to supply a delegate that implements what it means to sort specific elements, the sorting method doesn t have to know anything about this.

The same idea is used extensively with a lot of methods for LINQ. I.e. you pass in a delegate (or more commonly a lambda) which handles some specific task, and the LINQ method in question will call this in order to complete the task.

A delegate is a references type that invokes single/multiple method(s)through the delegate instance. It holds a reference of the methods.Delegates can be used to handle(call/invoke) multiple methods on a single event. Delegates can be used to define asynchronous methods. Here is an example for delegate First we create a class.In which we declare the delegate.and we create a method inside the class in which we invoke the delegate.

public class simpleinterest
{
    public delegate void intcal(double i);  //declare delegate
    public event intcal interest; //create delegate object
    public void calculate(double p, double n,double r)
    {
       interest(p*n*r/100);   //invoke delegate
    }

}

Inside our program we do the mapping.That is we specify which event will trigger when invoke the delegate.

    private void btn_Click(object sender, RoutedEventArgs e)
    {
        simpleinterest s1 = new simpleinterest();
        s1.interest+=new simpleinterest.intcal(s1_interest);//mapping

        s1.calculate(1000,3,10);

    }
    void s1_interest(double r)
    {
         MessageBox.Show("Amount:" + r.ToString());

    }

Delegates are reference type, a delegate refers to a method. This is called encapsulating the method. When you create a delegate you specify a method signature and return type. You can encapsulate any matching method with that delegate. You create a delegate with the delegate keyword, followed by a return type and the signatures of the methods that can be delegated to it, as in the following:

public delegate void HelloFunctionDelegate(string message);
class Program
{
 static void Main()
{
HelloFunctionDelegate del = new HelloFunctionDelegate(Hello);
del("Hello from Delegate");
}
public static void Hello(string strMessage)
{
 Console.WriteLine(strMessage);
}
}

Output is Hello from Delegate

Delagates in c# : it defines the signature of the method which it can invoke.In other words we can say that it wraps the reference of the method which it can call. Below are the uses of delegates :

  1. It provides the mechanism to implement the call back functionality in .NET framework.
  2. It provides the ability to call multiple methods sequentially.
  3. It has the ability to implement asynchronous method calling.

It supports both static and instance methods.

Below is the explanation how it works internally.

//Here is the declaration of the delegates.

public delegate void DisplayNamme(string name);

at run time CLR creates a class for the delegates as shown below.

public class DisplayNamme : System.MulticastDelegate{

   // It is a contructor
   public DisplayNamme(Object @object, IntPtr method);

   // It is the method with the same prototype as defined in the source code. 
   public void Invoke(String name);

// This method allowing the callback to be asynchronouslly.

 public virtual IAsyncResult BeginInvoke(String name, 
 AsyncCallback callback, Object @object); 

 public virtual void EndInvoke(IAsyncResult result); 

}

We can see it through ILDasm.exe tool. Use this tool to break the DLL.

Constructor have two parameters: IntPrt refers the name of the method that is passed to the function, and @object refers the reference of the object that is passed to the constructor implicitly.

CLR uses Invoke method of delegates to call the callback method.

Below is the implementation of callback method using delegates.

// Declare Delegates
    public delegate void DisplayNamme(string name);
    class Program
    {
       public static void getName(string name)
        {
            Console.WriteLine(name);
        }
       public static void ShowName(DisplayNamme dn, string name)
        {
        // callback method calling. We can call it in two ways. 
           dn(name);
          // or explicitly
            dn.Invoke(name);
    }
      static void Main(string[] args)
        {
            DisplayNamme delDN = getName;
            Program.ShowName(delDN, "CallBack");
            Console.ReadLine();
        }
    }

A Delegate is a reference type variable that points the reference to a method. All delegates are derived from System.Delegate class. For example in Windows Forms or WPF, a method event works with the concept of delegates. This is an example of using delagates in C# Introduction to delegates in C#





相关问题
Anyone feel like passing it forward?

I m the only developer in my company, and am getting along well as an autodidact, but I know I m missing out on the education one gets from working with and having code reviewed by more senior devs. ...

NSArray s, Primitive types and Boxing Oh My!

I m pretty new to the Objective-C world and I have a long history with .net/C# so naturally I m inclined to use my C# wits. Now here s the question: I feel really inclined to create some type of ...

C# Marshal / Pinvoke CBitmap?

I cannot figure out how to marshal a C++ CBitmap to a C# Bitmap or Image class. My import looks like this: [DllImport(@"test.dll", CharSet = CharSet.Unicode)] public static extern IntPtr ...

How to Use Ghostscript DLL to convert PDF to PDF/A

How to user GhostScript DLL to convert PDF to PDF/A. I know I kind of have to call the exported function of gsdll32.dll whose name is gsapi_init_with_args, but how do i pass the right arguments? BTW, ...

Linqy no matchy

Maybe it s something I m doing wrong. I m just learning Linq because I m bored. And so far so good. I made a little program and it basically just outputs all matches (foreach) into a label control. ...

热门标签