我在某处看到了这段代码并且想知道:何时以及为什么有人会做以下事情:
doSomething( (MyClass) null );
Run Code Online (Sandbox Code Playgroud)
你有没有这样做过?你能分享一下你的经历吗?
Joh*_*itb 128
如果doSomething重载,则需要显式转换null,MyClass以便选择正确的重载:
public void doSomething(MyClass c) {
// ...
}
public void doSomething(MyOtherClass c) {
// ...
}
Run Code Online (Sandbox Code Playgroud)
当你调用varargs函数时,你需要强制转换的非人为情况:
class Example {
static void test(String code, String... s) {
System.out.println("code: " + code);
if(s == null) {
System.out.println("array is null");
return;
}
for(String str: s) {
if(str != null) {
System.out.println(str);
} else {
System.out.println("element is null");
}
}
System.out.println("---");
}
public static void main(String... args) {
/* the array will contain two elements */
test("numbers", "one", "two");
/* the array will contain zero elements */
test("nothing");
/* the array will be null in test */
test("null-array", (String[])null);
/* first argument of the array is null */
test("one-null-element", (String)null);
/* will produce a warning. passes a null array */
test("warning", null);
}
}
Run Code Online (Sandbox Code Playgroud)
最后一行会产生以下警告:
Example.java:26:warning:非varargs调用varargs方法,最后一个参数的参数类型不精确;
转换java.lang.String为varargs调用
转换java.lang.String[]为非varargs调用并禁止此警告
Ere*_*nes 34
假设您有这两个函数,并假设它们接受null第二个参数的有效值.
void ShowMessage(String msg, Control parent);
void ShowMessage(String msg, MyDelegate callBack);
这两种方法的区别仅在于它们的第二个参数的类型.如果要使用其中一个null作为第二个参数,则必须将其null转换为相应函数的第二个参数的类型,以便编译器可以决定调用哪个函数.
要调用第一个函数:ShowMessage("Test", (Control) null);
对于第二个函数:ShowMessage("Test2", (MyDelegate) null);
| 归档时间: |
|
| 查看次数: |
19687 次 |
| 最近记录: |