【问题标题】:Need some help to understand what is done in the second line of code?需要一些帮助来理解第二行代码中做了什么?
【发布时间】:2016-07-14 04:26:14
【问题描述】:
 public <T> void addToRequestQueue(Request<T> req, String tag) {
    req.setTag(TextUtils.isEmpty(tag) ? TAG : tag);
    getRequestQueue().add(req);
}

第二行做了什么?我不明白这是什么(标签)?标签:标签。

这是完整的代码

{
import android.app.Application;
import android.text.TextUtils;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.toolbox.Volley;

public class AppController extends Application {

    public static final String TAG = AppController.class.getSimpleName();

    private RequestQueue mRequestQueue;

    private static AppController mInstance;

    @Override
    public void onCreate() {
        super.onCreate();
        mInstance = this;
    }

    public static synchronized AppController getInstance() {
        return mInstance;
    }

    public RequestQueue getRequestQueue() {
        if (mRequestQueue == null) {
            mRequestQueue = Volley.newRequestQueue(getApplicationContext());
        }

        return mRequestQueue;
    }

    public <T> void addToRequestQueue(Request<T> req, String tag) {
        req.setTag(TextUtils.isEmpty(tag) ? TAG : tag);
        getRequestQueue().add(req);
    }

    public <T> void addToRequestQueue(Request<T> req) {
        req.setTag(TAG);
        getRequestQueue().add(req);
    }

    public void cancelPendingRequests(Object tag) {
        if (mRequestQueue != null) {
            mRequestQueue.cancelAll(tag);
        }
    }
}

这里是完整的代码,现在告诉我,如果可以,请解释在该方法第二行中做了什么

【问题讨论】:

  • 我们怎么知道?这是你的代码。看起来像类请求的一些实例变量。如果足够通用,请提供完整的上下文。
  • 您是在问 ?: 运算符是如何工作的吗?
  • 是的,操作员是如何工作的以及该方法第二行的代码是做什么的
  • 表达式“b ? v1 : v2”计算布尔值“b”,如果为真,则表达式的值为 v1,否则为 v2。有点像“int questionmark (boolean b, int v1, int v2) { if (b) return v1; return v2; } 但它不限于 int——v1/v2 可以是任何类型。
  • 感谢 John ...感谢您提出这样的概念,非常感谢您的知识

标签: java string ternary-operator


【解决方案1】:

TAG 必须是String 类型的某个常量,代表标签的默认值,不管它是什么 - 像这样:

public static final String TAG = "<default-tag>";

这里的想法是使用作为第二个参数传递的值标记您的请求,即String tagConditional operator ?: 用于在不使用if/else 语句的情况下实现检查。

当在对addToRequestQueue 的调用中传递的tag 字符串恰好为空时,该方法将使用TAG 的值。

【讨论】:

  • 还请补充一下,这是三元或内联 if 运算符。还有一个解释这一点的链接。
【解决方案2】:

第二行的翻译

public static final String TAG = AppController.class.getSimpleName();

public <T> void addToRequestQueue(Request<T> req, String tag) {
    req.setTag("is tag empty?" yes, so use `TAG` : no, so use `tag`);
    getRequestQueue().add(req);
} 

换句话说:

if(tag.isEmpty()){
  res.setTag(TAG)

} else {
  res.setTag(tag)

}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-08-01
    • 2012-03-24
    • 2012-02-17
    • 1970-01-01
    • 1970-01-01
    • 2023-04-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多