允许在不相关的类和接口之间进行强制转换 [英] Allowing cast between non-related class and interface
本文介绍了允许在不相关的类和接口之间进行强制转换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
以下代码在Java和C#中编译,我不明白为什么:
The following code compile in java and C# and I can''t understand why:
public interface A
{
}
public class B
{
}
public class C
{
private void foo(A a)
{
B b = (B)a;
}
}
A
与B
毫无关系.如果将A
更改为class
而不是interface
,则代码将无法编译.为什么将A
声明为interface
会改变呢?
A
is not related to B
in any way. If I change A
to be a class
instead of an interface
the code will not compile. Why does declaring A
as an interface
change that?
推荐答案
编译时没有错误,因为B的派生类也可以具有已实现的接口A.编译器不会进行检查,但是如果您要对其进行测试并传递例如实现A但不是B的后代的类D,则会出现错误.
祝你好运!
There isn''t an error at compile time because a derived class of B can also have implemented interface A. The compiler doesn''t check that but if you would test it and pass a class D for example that implements A but is not a descendant of B, you would get an error.
Good luck!
这篇关于允许在不相关的类和接口之间进行强制转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文