How are delegates in C# better than function pointers in C/C++?

后端 未结 4 999
心在旅途
心在旅途 2020-12-17 15:46

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?

4条回答
  •  太阳男子
    2020-12-17 16:14

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

    • 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 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.

    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#.

    EDIT: 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.

提交回复
热议问题