- iOS/Objective-C 元类和类别
- objective-c - -1001 错误,当 NSURLSession 通过 httpproxy 和/etc/hosts
- java - 使用网络类获取 url 地址
- ios - 推送通知中不播放声音
我有一个方法 foo
void foo (String x) { ... }
void foo (Integer x) { ... }
我想从一个不关心参数的方法中调用它:
void bar (Iterable i) {
...
for (Object x : i) foo(x); // this is the only time i is used
...
}
上面的代码提示 foo(Object)
未定义,当我添加时
void foo (Object x) { throw new Exception; }
然后 bar(Iterable<String>)
调用它而不是 foo(String)
并抛出异常。
如何避免 bar(Iterable<String>)
有两个文本相同的定义?和 bar(Iterable<Integer>)
?
我以为我可以逃脱这样的事情
<T> void bar (Iterable<T> i) {
...
for (T x : i) foo(x); // this is the only time i is used
...
}
然后我得到 cannot find foo(T)
错误。
最佳答案
您面临的问题是重载方法是在编译时绑定(bind)的。在您的示例中,编译器试图找出要调用的 foo()
方法。但是,您的示例中 x
的最强静态类型是 Object,并且没有方法 foo(Object)
,因此编译器说它无法调用适当的方法.
如果添加foo(Object)
方法,无论x的实际运行时类型是什么,您将始终调用foo(Object)
方法。
这个问题扩展到使用泛型。因为 T
可以是任何类型,所以你必须有一个泛型方法 foo(T)
否则你的代码将无法编译。但是,如果您添加该方法,您将失去让这些方法辨别不同参数类型的能力,因为只会调用 foo(T)
。
解决此问题的唯一方法是逐案检查并像建议的其他答案一样转换。除非参数类型是您定义的类,并且它们都可以实现一个通用接口(interface)。然后你可以这样做:
interface ArgumentType {
void callback(FooClass c);
}
class YourClassA implements ArgumentType {
void callback( FooClass c ) {
c.foo( this );
}
}
FooClass
仍然需要为 ArgumentType
的每个实现类提供一个 foo()
方法,但是这样您就可以进行选择类型不可知。
关于java - 如何从不可知函数调用多态函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11109429/
我来自 Asp.Net 世界,试图理解 Angular State 的含义。 什么是 Angular 状态?它类似于Asp.Net中的ascx组件吗?是子页面吗?它类似于工作流程状态吗? 我听到很多人
我一直在寻找 3 态拨动开关,但运气不佳。 基本上我需要一个具有以下状态的开关: |开 |不适用 |关 | slider 默认从中间开始,一旦用户向左或向右滑动,就无法回到N/A(未回答)状态。 有人
我是一名优秀的程序员,十分优秀!