开发者

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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜