简体   繁体   English

C ++ / CLI和C#,“委托”代表的功能,什么是独家新闻?

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

In C# 2.0, I can do the following: 在C#2.0中,我可以执行以下操作:


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: 试图在C ++ / CLI中实现相同的功能,我必须这样做:


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. 显然,我可以在C#中创建一个新的委托实例,而不是在那里发生的事情。 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? 在C#世界中是否存在某种神奇的东西,C ++ / CLI中不存在允许该强制转换工作的魔法? 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++ 在C#世界中是否存在某种在C ++中不存在的魔法

Yes. 是。 Starting with C#2 you can simply say: 从C#2开始,您可以简单地说:

  MyDelegate del = SomeFunction;

And the compiler rewrites it to the long (C#1) form: 并且编译器将其重写为long(C#1)形式:

 MyDelegate del = new MyDelegate (SomeFunction);

You don't have that support in C++/CLI, but it's just a notational difference. 您在C ++ / CLI中没有这种支持,但它只是一个符号差异。 No big deal. 没什么大不了。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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