什么是“字符串...params“的意思是如果作为参数传递?

2022-09-03 04:10:07

我在网上找到了这个代码,有1个部分我不明白。对于方法 doInBackground,传递的参数是 。有人可以向我解释一下这意味着什么吗?什么?String... params...

public class AsyncHttpPost extends AsyncTask<String, String, String> {
    private HashMap<String, String> mData = null;// post data

    /**
     * constructor
     */
    public AsyncHttpPost(HashMap<String, String> data) {
        mData = data;
    }

    /**
     * background
     */
    @Override
    protected String doInBackground(String... params) {
        byte[] result = null;
        String str = "";
        HttpClient client = new DefaultHttpClient();
        HttpPost post = new HttpPost(params[0]);// in this case, params[0] is URL
        try {
            // set up post data
            ArrayList<NameValuePair> nameValuePair = new ArrayList<NameValuePair>();
            Iterator<String> it = mData.keySet().iterator();
            while (it.hasNext()) {
                String key = it.next();
                nameValuePair.add(new BasicNameValuePair(key, mData.get(key)));
            }

            post.setEntity(new UrlEncodedFormEntity(nameValuePair, "UTF-8"));
            HttpResponse response = client.execute(post);
            StatusLine statusLine = response.getStatusLine();
            if(statusLine.getStatusCode() == HttpURLConnection.HTTP_OK){
                result = EntityUtils.toByteArray(response.getEntity());
                str = new String(result, "UTF-8");
            }
        }
        catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        catch (Exception e) {
        }
        return str;
    }

    /**
     * on getting result
     */
    @Override
    protected void onPostExecute(String result) {
        // something...
    }
}

答案 1

这三个点停留在 。您可以像访问一样访问它。vargarsString[]

如果一个方法将 varargs 作为参数,则可以使用 vargars 类型的多个值来调用它:

public void myMethod(String... values) {}

你可以打电话喜欢myMethod("a", "b");

在 myMethod 中等于“a”,等于 “b”。如果你有一个具有多个参数的方法,vargars参数必须是最后一个:例如:values[0]values[1]

public void myMethod(int first, double second, String... values) {}

答案 2
 doInBackground(String... params)
 // params represents a vararg.
 new AsyncHttpPost().execute(s1,s2,s3); // pass strings to doInbackground
 params[0] is the first string
 params[1]  is the second string 
 params[2]  is the third string 

http://developer.android.com/reference/android/os/AsyncTask.html#doInBackground(参数...

异步任务的参数传递给doInBackground


推荐