简体   繁体   中英

C++/CLI and C#, “Casting” Functions to Delegates, What's the scoop?

In C# 2.0, I can do the following:


public class MyClass
{
     delegate void MyDelegate(int myParam);

     public MyClass(OtherObject obj)
     {
//THIS IS THE IMPORTANT PART
           obj.SomeCollection.Add((MyDelegate)MyFunction);
     }

     private void MyFunction(int myParam);
     {
           //...
     }
}

Trying to implement the same thing in C++/CLI, it appears I have to do:


MyDelegate del = gcnew MyDelegate(this, MyFunction);
obj->SomeCollection->Add(del);

Obviously I can create a new instance of the delegate in C# as well instead of what's going on up there. Is there some kind of magic going on in the C# world that doesn't exist in C++/CLI that allows that cast to work? Some kind of magic anonymous delegate? Thanks.

Is there some kind of magic going on in the C# world that doesn't exist in C++

Yes. Starting with C#2 you can simply say:

  MyDelegate del = SomeFunction;

And the compiler rewrites it to the long (C#1) form:

 MyDelegate del = new MyDelegate (SomeFunction);

You don't have that support in C++/CLI, but it's just a notational difference. No big deal.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM