fep*_*piv 12 c# inheritance casting interface
我希望有人可以解释我正在做出的错误假设.在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();
}
}
Run Code Online (Sandbox Code Playgroud)
我试图理解为什么铸造成功.是的,该类实现了两个接口,但我认为由于第一个变量被声明为IFirstInterface(它不从ISecondInterface继承),所以转换仍然会失败.
我也尝试过以其他方式重构我的代码,例如不使用'as',但是演员仍然是成功的.
我错过了什么?
从您的示例中,您应该在调用任何功能之前测试类型类型.第一个创建将创建一个支持两个接口的完全限定的"InterfaceImplementation".但是,您将它放入仅第一个接口的声明类型.因此,从"第一个"对象的角度来看,它只关心与IFirstInterface实现相关的任何事情.
现在,第二个......即使你已经创建了这个对象,你仍然可以问...顺便问一下......你也是第二个接口吗?如果是这样,这样做......
IFirstInterface first = new InterfaceImplementation();
if( first is ISecondInterface )
// typecast since the second interface is legit, then call it's method 2
((ISecondInterface)first).Method2();
Run Code Online (Sandbox Code Playgroud)