AsyncTask
参数中使用varargs
的原因?例如,方法execute()
,doInBackground()
和publishProgress()
都使用[Type]...
符号。我认为这使得它更难使用,所以他们一定有一些好的理由,我可能忽略了些什么?
因此,我们要么没有参数,要么有一个或多个参数。让我们分解一下:
No parameters (easy):
Params
parameter isVoid
and that's it. (The methods cannot use it... so that's pretty safe.)One parameter: Here, I at least, feel the need to make a check at the beginning of the
doInBackground()
method. For example, here is a task receiving anInteger
and producing a result of typeDouble
:public Double doInBackground(Integer... myParameters) { // we are only expecting one parameter if (myParameters.length != 1) throw new IllegalArgumentException("!= 1"); return 100d * myParameters[0]; }
More than one parameter. Now here must be where Google made the right choice? But as I see it's either you are interested in a list of parameters of the same type, or you want different types of parameters. Google only addressed one of these cases (with different types you need some kind of common interface. In many cases I end up with
Object...
and that isn't really type safe...)
那么,如果我们完全删除varargs
会有什么问题呢?这是一些方法的子集:
class AsyncTask<Param, Progress, Result> {
abstract Result doInBackground(Param param);
void publishProgress(Progress progress) { ... }
}
这对以上所有情况都适用。例如,如果我们想处理参数数组,我们只需使用数组类型
param
:class MyAsyncTask extends AsyncTask<String[], Integer, String> {
String doInBackground(String[] param) {
return Arrays.toString(param);
}
}
我不认为它有任何实际应用价值。但我相信我可能错过了某些需要了解的关于curia的东西。:)
AsyncTask
没有任何具体关系。你可能会抱怨使用Restaurant
类的可变参数。如果你的问题集中在可变参数对AsyncTask
如何处理线程间通信的影响上,那么它可能不是一个重复的问题。但就目前而言,在我看来,我引用的问题中提供的答案似乎也可以回答这个问题。 - CommonsWareAsyncTask
的原作者Romain Guy加入这个问题的讨论。关于为什么在这种情况下使用可变参数的答案最接近的是为什么一般会使用可变参数的答案,该问题已在链接的问题中得到解答。 - CommonsWare