【发布时间】:2009-03-06 09:10:52
【问题描述】:
我在 .NET 中设计 win 表单时使用了委托...即拖放按钮、双击并填写 myButton_click 事件。我想了解如何在 C# 中创建和使用用户定义的委托。
如何在 C# 中使用和创建用户定义的委托?
【问题讨论】:
我在 .NET 中设计 win 表单时使用了委托...即拖放按钮、双击并填写 myButton_click 事件。我想了解如何在 C# 中创建和使用用户定义的委托。
如何在 C# 中使用和创建用户定义的委托?
【问题讨论】:
我建议阅读有关该主题的教程。
基本上,您声明一个委托类型:
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");
}
这是基本用法。
【讨论】:
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());
}
【讨论】:
不是完全重复(找不到重复),但这里有很多关于 SO 的信息,请尝试
Differnce between Events and Delegates上手,接着看
Whis is this delegate doing . . .
希望这些帮助
【讨论】:
要获得广泛的答案,请通过mohamad halabi查看article。 要获得更简短的答案,请检查 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
【讨论】: