我希望有人能够解释一下我犯了哪些错误假设。在C# 4.0中,我有两个接口和一个实现它们的类。在一个方法中,我声明了一个类型为第一个接口的变量,并使用实现两个接口的类进行实例化,并可以将其成功地强制转换为第二个接口,就像下面的代码一样:
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”,但转换仍然成功。
我错过了什么?