简体   繁体   English

如何摆脱ClassCastException

[英]How to Get rid of ClassCastException

假设我有2个完全不同的用户定义类AB

A a = new A();

B b = new B();

. . .

. . .

a = (A) b; //I'm pretty sure this raises a ClassCastException, but how to deal with this issue?

You can't, unless B derives from A. 除非B衍生自A,否则您就不能这样做。
That's the point of a ClassCastException. 这就是ClassCastException的意义。

But since A and B are totally different, why would you want to convert them in the first place? 但是,由于A和B完全不同,为什么首先要转换它们?

Testing before assign the variable. 在分配变量之前进行测试。

In java: 在Java中:

if(a instanceof B)
    b = (B) a;

In C#: 在C#中:

if(a is B)
    b = (B) a;

But as someone mentioned if you do not derive the class a and b from c I cant see to much benefit of this assignment. 但是正如有人提到的,如果您不从c派生a和b类,我看不出这种分配有多大好处。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM