kat*_*tit 6 c# java android delegates
我是Java新手,但我需要编写类似C#代码的东西(这是手工打造的原型,只是为了说明我需要的东西)
private void ParentFunc()
{
var worker = new WorkerClass()
worker.DoWork(e => console.Write("Progress" + e));
}
public class WorkerClass()
{
public method DoWork(Action<int> callback)
{
for (int i=1; i<1000; i++) callback.Invoke(i);
}
}
Run Code Online (Sandbox Code Playgroud)
小解释.我AsyncTask在android中使用并在处理器外部进行调用,但希望它们能够发出信号,以便我可以publishProgress.我不想把界面放在我的身上AsyncTask
由于不支持闭包,您必须使用接口和匿名内部类.
private void ParentFunc {
WorkerClass worker = new WorkerClass();
worker.doWork(new Callback<Integer>() {
public void invoke(Integer arg) {
System.out.println("Progress" + arg);
}
});
}
public class WorkerClass {
public doWork(Callback<Integer> callback) {
for (int i=1; i<1000; i++) callback.invoke(i);
}
}
public interface Callback<T> {
public void invoke(T arg);
}
Run Code Online (Sandbox Code Playgroud)
在java中,您使用实现接口的匿名类.这有点冗长,但它运作得很好:
interface MyAction {
void doit(String str);
}
class WorkerClass {
void doWork(MyAction action);
}
void main(String args[]) {
WorkerClass worker = new WorkerClass();
worker.doWork(new MyAction {
public void doit(String e) {
System.out.println("Progress" + e)
}
});
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1883 次 |
| 最近记录: |