【发布时间】:2012-05-12 05:37:28
【问题描述】:
我希望这里有人可以解释我所做的错误假设。在 C# 4.0 中,我有 2 个接口和一个实现它们的类。在一个方法中,我用第一个接口的类型声明了一个变量,使用实现这两个接口的类对其进行实例化,并可以以某种方式成功地将其转换为第二个接口,如下面的代码:
public interface IFirstInterface
{
void Method1();
}
public interface ISecondInterface
{
void Method2();
}
public class InterfaceImplementation : IFirstInterface, ISecondInterface
{
public void Method1() { }
public void Method2() { }
}
public class SomeClass
{
public void SomeMethod()
{
IFirstInterface first = new InterfaceImplementation();
first.Method1();
// Shouldn't the next line return null?
ISecondInterface second = first as ISecondInterface;
// second is not null and the call to Method2() works fine
second.Method2();
}
}
我正试图了解为什么选角成功。是的,该类实现了这两个接口,但我认为由于第一个变量被声明为 IFirstInterface(它不是从 ISecondInterface 继承的),因此转换应该仍然失败。
我也尝试过以其他方式重构我的代码,例如不使用“as”,但转换仍然成功。
我错过了什么?
【问题讨论】:
标签: c# inheritance interface casting