如何在C#中使用和创建用户定义的委托?

时间:2009-03-06 09:10:52

标签: c# delegates

我在.NET中设计win表单时使用过代理...即拖放按钮,双击,然后填写myButton_click事件。我想了解如何在C#中创建和使用用户定义的委托。

如何在C#中使用和创建用户定义的委托?

4 个答案:

答案 0 :(得分:8)

我建议阅读有关该主题的教程。

基本上,您声明委托类型:

public delegate void MyDelegate(string message);

然后你可以直接分配和调用它:

MyDelegate = SomeFunction;
MyDelegate("Hello, bunny");

或者你创建一个事件:

public event MyDelegate MyEvent;

然后你可以像这样在外面添加一个事件处理程序:

SomeObject.MyEvent += SomeFunction;

Visual Studio对此很有帮助。输入+ =后,只需按tab-tab,它就会为你创建处理程序。

然后你可以从对象内部触发事件:

if (MyEvent != null) {
    MyEvent("Hello, bunny");
}

这是基本用法。

答案 1 :(得分:1)

public delegate void testDelegate(string s, int i);

private void callDelegate()
{
    testDelegate td = new testDelegate(Test);

    td.Invoke("my text", 1);
}

private void Test(string s, int i)
{
    Console.WriteLine(s);
    Console.WriteLine(i.ToString());
}

答案 2 :(得分:1)

不完全重复(找不到重复)但有关SO的大量信息,请尝试

Differnce between Events and Delegates开始使用,然后查看

When to use . . .

What are Closures

Whis is this delegate doing . . .

希望这些帮助

答案 3 :(得分:1)

要获得广泛的答案,请article查看mohamad halabi。 对于较短的答案,请从c:/ Program Files / Microsoft Visual Studio 9.0 / Samples / 1033 /文件夹中查看此略微修改的示例......

using System;
using System.IO; 


namespace DelegateExample
{
  class Program
  {
    public delegate void PrintDelegate ( string s );

    public static void Main ()
    {
      PrintDelegate delFileWriter = new PrintDelegate ( PrintFoFile );
      PrintDelegate delConsoleWriter = new PrintDelegate ( PrintToConsole);
      Console.WriteLine ( "PRINT FIRST TO FILE by passing the print delegate -- DisplayMethod ( delFileWriter )" );

      DisplayMethod ( delFileWriter );      //prints to file
      Console.WriteLine ( "PRINT SECOND TO CONSOLE by passing the print delegate -- DisplayMethod ( delConsoleWriter )" );
      DisplayMethod ( delConsoleWriter ); //prints to the console
      Console.WriteLine ( "Press enter to exit" );
      Console.ReadLine ();

    }

    static void PrintFoFile ( string s )
    {
      StreamWriter objStreamWriter = File.CreateText( AppDomain.CurrentDomain.BaseDirectory.ToString() + "file.txt" );
      objStreamWriter.WriteLine ( s );
      objStreamWriter.Flush ();
      objStreamWriter.Close ();
    }


    public static void DisplayMethod ( PrintDelegate delPrintingMethod )
    { 
      delPrintingMethod( "The stuff to print regardless of where it will go to" ) ;
    }

    static void PrintToConsole ( string s )
    {
      Console.WriteLine ( s );    
    } //eof method 
  } //eof classs 
} //eof namespace