我如何实例化?包含代码 [英] How I instantiate? Include code
本文介绍了我如何实例化?包含代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
编译器不允许我在最后一行保留< X,Y>,我不明白为什么。
The compiler won't permit me to keep <X,Y> on the last line and I do not understand why.
我如何得到这样的要编译的通用构造?
How do I get such a generic construction to compile?
我尝试将代码更改为:
X a = new A<X,Y>(); // "Type mismatch: cannot convert from A<X,Y> to X"
Y b = new B<X,Y>(); // "Type mismatch: cannot convert from B<X,Y> to Y"
W<X,Y> s = new M<X,Y>(a,b); // no error
我有点迷失 - 请帮忙!
I am a bit lost - please help!
推荐答案
的构造函数M< X,Y>
预计会收到 X
和 Y
,但你'试图给它一个 IA< X,Y>
和 IB< X,Y>
。必要的关系是相反的; X
是 IA< X,Y>
,但反之亦然, Y
类似。
The constructor of M< X, Y >
expects to receive an X
and a Y
, but you're trying to give it an IA< X, Y >
and an IB< X, Y >
. The necessary relationships are reversed; X
is an IA< X, Y >
, but not vice-versa, and similarly for Y
.
以下编译,但似乎对你所追求的内容没有足够的限制:
The following compiles, but appears to be not restrictive enough for what you are after:
class A<X extends IA<X,Y>, Y extends IB<X,Y>> implements IA<X,Y>{}
class B<X extends IA<X,Y>, Y extends IB<X,Y>> implements IB<X,Y>{}
interface IA<X extends IA<X,Y>, Y extends IB<X,Y>> {}
interface IB<X extends IA<X,Y>, Y extends IB<X,Y>> {}
class M<X extends IA<X,Y>, Y extends IB<X,Y>> extends W<X,Y>{
public M(IA<X,Y> x, IB<X,Y> y){} // this is the only change
}
class W<X extends IA<X,Y>, Y extends IB<X,Y>> {}
//To my check class code:
public <X extends IA<X,Y>, Y extends IB<X,Y>> void check() {
IA<X,Y> a = new A<X,Y>();
IB<X,Y> b = new B<X,Y>();
W<X,Y> s = new M<X,Y>(a,b);
}
这篇关于我如何实例化?包含代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文