在Android中我可以使用这样的监听器:
Class1.java:
public class Class1 {
public Class1() {
Class2 c = new Class2();
c.setOnFinishListener(new Class2.OnFinishListener() {
@Override
void onFinish(String result) {
// My result's handling here
}
});
}
}
Class2.java:
public class Class2 {
private OnFinishListener mOnFinishListener;
public void setOnFinishListener(OnFinishListener onFinishListener) {
mOnFinishListener = onFinishListener;
}
private void someMethod() {
String result="Result here";
if (mOnFinishListener != null) mOnFinishListener.onFinish(result);
}
public interface OnFinishListener {
void onFinish(String result);
}
}
C#中是否提供此类内容?如何使用C#实现这样的类之间的通信?
答案 0 :(得分:1)
C#中推荐的方法是使用事件:
public class Class1
{
public Class1()
{
var c = new Class2();
c.OnFinish += result =>
{
// My result handling here
};
}
}
public class Class2
{
public event Action<string> OnFinish;
private void SomeMethod()
{
string result = "Result here";
var eventHandler = this.OnFinish;
if (eventHandler != null)
{
eventHandler(result);
}
}
}