C#中的代表和事件 [英] Delegate and event in C#
问题描述
在哪种情况下我们基本上使用dot net.plz中的委托解释我的实例。
In which scenario we basicaly use delegate in dot net.plz explain me with live example.
推荐答案
委托是一种类型安全地封装了一个方法,类似于 C 和 C ++ 中的函数指针。与C函数指针不同,委托是面向对象,类型安全和安全。委托的类型由委托的名称定义。
一个小例子:
A delegate is a type that safely encapsulates a method, similar to a function pointer in C and C++. Unlike C function pointers, delegates are object-oriented, type safe, and secure. The type of a delegate is defined by the name of the delegate.
An small example:
// Create a method for a delegate.
public static void DelegateMethod(string message)
{
System.Console.WriteLine(message);
}
现在声明并打电话..
And now declare and just call..
// Instantiate the delegate.
Del handler = DelegateMethod;
// Call the delegate.
handler("Hello World");
使用代表的一些范围:
1。事件处理程序(用于GUI等)
2。 启动线程
3。回调(例如异步API)
4。 LINQ和类似(List.Find等)
5。我想在其他任何地方有效地应用模板代码,里面有一些专门的逻辑(代表提供专业化) />
您可以在此查看一些实时示例:
代表在C#中的权力 [ ^ ]
C# - 代表101 - 一个实际例子 [ ^ ]
http://stackoverflow.com/questions/2019402/when-why-to-use-delegates [ ^ ]
Some scopes where delegates are used:
1. Event handlers (for GUI and more)
2. Starting threads
3. Callbacks (e.g. for async APIs)
4. LINQ and similar (List.Find etc)
5. Anywhere else where I want to effectively apply "template" code with some specialized logic inside (where the delegate provides the specialization)
Some live examples you can view here:
The Power of Delegates in C#[^]
C# - Delegates 101 - A Practical Example[^]
http://stackoverflow.com/questions/2019402/when-why-to-use-delegates[^]
请参阅以下链接,谢尔盖以非常简洁的方式解释了这一点。
C#.NET中代理人的优势是什么? [ ^ ]
代表的额外优势是什么 [ ^ ]
为什么我们使用代表 [< a href =http://www.codeproject.com/Questions/415799/Why-we-use-Delegatestarget =_ blanktitle =New Window> ^ ]
动态方法调度程序 [ ^ ]
问候......:笑:
Refer to below links where Sergey explained it in very concise way.
What are the advantages of delegates in C#.NET?[^]
What is the Extra Advantage of Delegate[^]
Why we use Delegates[^]
Dynamic Method Dispatcher[^]
Regards.. :laugh:
请看 http:// zetcode .com / lang / csharp / delegates / [ ^ ]
这篇关于C#中的代表和事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!