简体   繁体   English

从C ++迁移到C#(回叫)

[英]Migration C++ to C# (CALLBACK)

I am currently doing a migration of c++ to c # and I presented the following problem which I have not the faintest idea as can be done within c # 我目前正在将c ++迁移到c#,并提出了以下问题,但我没有最模糊的想法,因为可以在c#中完成

typedef void (CALLBACK *funtion1)(int a , int b);

void SetCallBackFuntion(funtion1 pfn);


void something(){

obj->SetCallBackFuntion(&funtion1);

}

There are a few ways to achieve the equivilant behaviour in C# depending on how you want it to work and what version of .NET you're targeting. 有几种方法可以实现C#中的等价行为,具体取决于您希望它如何工作以及所针对的.NET版本。 The easiest method is to use an Action . 最简单的方法是使用Action

To implement this using C# standards it should first be noted that it fits better as a property rather than a method. 要使用C#标准实现此功能,首先应注意,它更适合作为属性而不是方法。 Also, because the callback doesn't return a value it's referred to as a method, not a function. 另外,由于回调不返回值,因此称为方法而不是函数。 So the code above would look something like this: 因此,上面的代码如下所示:

public Action<int,int> CallBack { set; }

public void Something()
{
    obj.CallBack = function1;
}

And the code to call the callback would do something like this: 调用回调的代码将执行以下操作:

if(CallBack != null)
    CallBack(1, 2);

Another approach is to use a delegate , which is just a slightly more verbose way of describing an Action and compatible with older versions of .NET. 另一种方法是使用委托 ,这只是描述Action的一种更为冗长的方式,并且与.NET的较早版本兼容。 It also translates more closely with the C++ code. 它还与C ++代码更紧密地转换。 Note: Although this would technically work (assuming you implemented the rest correctly) it's not normally regarded as good practice. 注意:尽管从技术上讲这是可行的(假设您正确地实现了其余部分),但通常不将其视为良好实践。 I just wanted to show you a quick and dirty way. 我只是想向您展示一种快速而肮脏的方式。

public delegate void CallBack(int x, int y);

private void SetCallBackFuntion(CallBack pfn)
{
}

private void Something()
{
    obj.SetCallBackFuntion(funtion1);
}

A third approach is to use interfaces. 第三种方法是使用接口。 You could describe an interface with your method signature like this: 您可以使用以下方法签名来描述接口:

public interface IMyInterface
{
    void CallBack(int x, int y);
}

and then you could have a property on your class similar to the Action but using the interface instead. 然后您可以在类上具有类似于Action的属性,但改用接口。

public IMyInterface CallBackObject { set; }

public void Something()
{
    obj.CallBackObject = someObject;
}

if(CallBackObject != null)
    CallBackObject.CallBack(1, 2);

The final approach that comes to mind is to use event handlers, but since they are more useful when you have multiple subscribers to your callback, I won't cover them here. 我想到的最后一种方法是使用事件处理程序,但是由于在回调有多个订阅者时它们更有用,因此在此不做介绍。

可以使用委托简单地用C#编写

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

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