gpt4 book ai didi

Android 和通用模式

转载 作者:太空宇宙 更新时间:2023-11-03 13:11:34 24 4
gpt4 key购买 nike

我最近在 android 类(Intent)中发现了以下模式:

AClass c = data.getParcelableExtra("name");

签名:

public <T extends Parcelable> T getParcelableExtra(String name)

沿着小路往下走​​有一个 Actor :

public <T extends Parcelable> T getParcelable(String key) {
unparcel();
Object o = mMap.get(key);
if (o == null) {
return null;
}
try {
return (T) o;
} catch (ClassCastException e) {
typeWarning(key, o, "Parcelable", e);
return null;
}
}

调用 getParcelableExtra 的代码中缺少强制转换令我震惊。我发现结构“类似于”findViewById(int id)。为什么没有使用以下签名实现 findViewById:

public <T extends View> T genericsFindViewById(int id) {
switch (id){ //Bogus method body as example
case 1:
return (T) new TextView(getActivity());
case 2:
return (T) new RecyclerView(getActivity());
default:
return (T) new ImageView(getActivity());
}
}

//Examples
TextView t = genericsFindViewById(1);
RecyclerView r = genericsFindViewById(2);
ImageView i = genericsFindViewById(4);
TextView t2 = genericsFindViewById(4); // this gives ClassCastException
//But the following would as well:
TextView t3 = (TextView) rootView.findViewById(R.id.image_view);

我没问题,我只是想了解为什么他们在一种情况下而不是另一种情况下在 android 结构中进行内部转换?

最佳答案

这可能是由于历史原因,这些代码不是同时编写的,决定风格时考虑的因素不一样等。

昨天在 Google I/O 2017 上他们宣布 Android O api 中的 View.findViewById 将声明为 public <T extends View> findViewById(int id) .

如图所示 here : enter image description here

关于Android 和通用模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44042935/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com