如何代表在C#中的C / C ++比函数指针更好? [英] How are delegates in C# better than function pointers in C/C++?

查看:143
本文介绍了如何代表在C#中的C / C ++比函数指针更好?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在C#中的代表提供了类似的功能在C函数指针我听到有人说:C#代表们实际上比C函数指针更好。怎么来的?请举个例子来说。

The delegates in C# offer similar functionality as function pointers in C. I heard someone saying "C# delegates are actually better than function pointers in C". How come? Please explain with an example.

推荐答案

好是主观的 - 但主要区别是:

"Better" is subjective -- but the main differences are:

  • 类型安全。委托是不仅保证引用有效的方法,它是保证提及的方法具有正确的签名。
  • 这是一个的的约束的方法指针 - 也就是说,委托可以指向在其上调用该委托的特定对象。因此,动作<字符串> 代表可以参考 alice.GetName bob.GetName 而不仅仅是 Person.GetName 。这的也许的类似于C ++指针成员 - 我不知道
  • Type safety. A delegate is not only guaranteed to refer to a valid method, it is guaranteed to refer to a method with the correct signature.
  • It's a bound method pointer -- that is, the delegate can point to a specific object on which to call the delegate. Thus, an Action<string> delegate could refer to alice.GetName or bob.GetName rather than just Person.GetName. This might be similar to C++ "pointer to member" -- I'm not sure.

此外,C#语言支持通过代表匿名方法和lambda EX pressions关闭 - 即捕捉申报程序,这代表当它后来被执行可以引用局部变量。这并不是严格意义代表的一个特点 - 它是由C#编译器做了一些神奇的匿名方法和lambda EX pressions启用 - 但它仍然值得一提,因为它使很多功能成语在C#。

In addition, the C# language supports closures through delegates to anonymous methods and lambda expressions -- i.e. capturing local variables of the declaring procedure, which delegate can reference when it later gets executed. This isn't strictly speaking a feature of delegates -- it's enabled by the C# compiler doing some magic on anonymous methods and lambda expressions -- but it's still worth mentioning because it enables a lot of the functional idioms in C#.

编辑:作为CWF注意到评论中,C#代表另一个可能的优点是委托类型的声明更容易被很多人阅读。这可能是熟悉当然和经验,的问题。

As CWF notes in comments, another possible advantage of C# delegates is that the delegate type declarations are easier for many people to read. This may be a matter of familiarity and experience, of course.

这篇关于如何代表在C#中的C / C ++比函数指针更好?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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