我有一个类,其中有一个接口,如下所示:
public class hcmTerminal {
... Code
public interface onDataReceived {
void isCompleted(bool done);
}
}
在这堂课内我有公共财产:
public onDataReceived mDataReceived;
然后我有一个设置委托的功能:
public void setDataReceived(onDataReceived dataReceived) { mDataReceived = dataReceived; }
在hcmTerminal类中,我正在调用委托:
mDataReceived.isCompleted(true);
但我无法弄清楚当该委托被调用时实际得到的语法,在java中我可以去:
myTerminal.setDataReceived(new hcmTerminal.onDataReceived(){
@Override
public void isCompleted(boolean done){
... Code
}
});
但如果我在C#中尝试,我会得到:
无法创建抽象或接口的实例 ' hcmTerminal.onDataReceived'
我以前不必在C#中创建一个界面。这段代码来自我在Java中实现它的方式。
答案 0 :(得分:2)
定义实现接口的类:
class MyDataReceived : hcmTerminal.onDataReceived {
public void isCompleted(bool done) {
Console.WriteLine("call to isCompleted. done={0}", done);
}
}
现在您可以致电myTerminal.setDataReceived(new MyDataReceived())
但是,这是一个用C#编码的Java解决方案,而不是" native" C#解决方案。更好的方法是定义代理来代替接口:
public class HcmTerminal {
... Code
public delegate void OnDataReceived(bool done);
}
这将允许您使用多个C#功能来提供委托实现,例如提供方法名称,提供匿名委托或使用lambda:
myTerminal.setDataReceived((done) => {
Console.WriteLine("call to isCompleted. done={0}", done);
});
答案 1 :(得分:2)
通过使用事件,您可以通过
完成该事件 class HcmTerminal {
public event Action<bool> OnDataReceived;
public void Launch()
{
OnDataReceived?.Invoke(true /*or false*/);
}
}
然后你可以这样做:
var myTerminal = new HcmTerminal();
myTerminal.OnDataReceived += (isCompleted) => {};