What is the difference between delegate in c# and function pointer in c++? [duplicate]

痴心易碎 提交于 2019-12-20 10:07:10

问题


Possible Duplicate:
are there function pointers in c#?

I'm interested in finding the difference between delegate in C# and function pointer in C++.


回答1:


A delegate in C# is a type-safe function pointer with a built in iterator.

It's guaranteed to point to a valid function with the specified signature (unlike C where pointers can be cast to point to who knows what). It also supports the concept of iterating through multiple bound functions.

In C#, delegates are multi-cast meaning they can iterate through multiple functions. For example:

class Program
{
   delegate void Foo();

   static void Main(string[] args)
   {
      Foo myDelegate = One;
      myDelegate += Two;

      myDelegate(); // Will call One then Two
   }

   static void One()
   {
      Console.WriteLine("In one..");
   }

   static void Two()
   {
      Console.WriteLine("In two..");
   }
}



回答2:


Delegates in C# can be either synchronous or asynchronous; C++ function pointers are synchronous unless you write your own multi-threading capability.

A pointer in C/C++ needn't refer to a full-blown object. C had function pointers and no object-oriented language support. Delegates are true function objects.



来源:https://stackoverflow.com/questions/8097244/what-is-the-difference-between-delegate-in-c-sharp-and-function-pointer-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!