为什么委托需要在C#中调用方法 [英] Why delegates need in C# for invoking method

查看:168
本文介绍了为什么委托需要在C#中调用方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

c#有两种类型的成员 - 静态成员和实例成员

用于使用类的名称调用静态成员

用于使用类的实例调用实例成员

但为什么你需要c#中的代表来调用成员









请帮帮我。



谢谢你



什么我试过了:



用于使用类的名称调用静态成员

用于使用类的实例调用实例成员

但为什么你需要c#中的代理来调用成员

c# has two types of members--static and instance members
For invoking static members using name of the class
For invoking instance members using instance of the class
but why do u need delegates in c# for invoking members




please help me.

thank u

What I have tried:

For invoking static members using name of the class
For invoking instance members using instance of the class
but why do u need delegates in c# for invoking members

推荐答案

代表实际上是函数指针 - 所以他们让你存储变量中的函数并在以后执行它。



这用于事件处理程序:单击一个按钮,会引发Click事件。

系统查看Click事件处理程序变量,并执行它在那里找到的函数。 (这是一个可怕的简化,但它现在也会这样做。)



这也允许你在运行时将一个函数传递给一个方法,这非常方便。

例如,您可以编写一个打印文档的方法 - 并将其在运行时实际打印到屏幕的函数或打印到打印机的函数或文件传递给它,或者一个数据库,或者......所有这些都不需要以任何方式改变决定在页面上打印什么的方法 - 它不需要知道打印到什么,它只是从委托中调用适当的函数你通过它。
Delegates are effectively "pointers to functions" - so they let you store a "function" in a variable and execute it at a later time.

This is used for event handlers: A button is clicked, which raises a Click event.
The system looks at the Click event handler variable, and executes the function it finds in there. (That's a horrible simplification but it'll do for now.)

This also allows you to pass a function to a method at run time, and that's very handy.
For example, you can write a method that prints a document - and pass it the function that actually prints to the screen at run time, or the function that prints to the printer, or a file, or a database, or ... all without having to change in any way the method that decides what to print where on a page - it doesn't need to know what it is printing to, it just calls the appropriate function from the delegate you passed it.


你的问题让我相信你需要为理解C#和.NET基础知识找到更坚实的基础。我建议你买一本好书,然后学习。



这里有两本免费书:[ ^ ],[ ^ ]



C#中的静态类型,在类中定义,可以被认为是类的实例 ,而不是类实例的成员实例。静态成员本质上是 singleton 对象:无论创建了多少个Class实例,每个静态成员中只有一个。
Your question leads me to believe you need to get a more solid basis for understanding C# and .NET fundamentals. I suggest you get a good book, and study.

Here are two free books: [^], [^]

Static Types in C#, defined in a Class, can be thought of as "instances of the Class," rather than instances of members of a Class instance. Static members are inherently singleton objects: no matter how many instances of a Class are created, there will be only one of each static member.


这篇关于为什么委托需要在C#中调用方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆