我们可以使用接口变量调用其接口中未定义的实现类中的方法吗?

Fak*_*war 5 c# oop

是否可以在接口的实现类中调用一个方法,该接口未使用接口变量在接口中定义,如下所示:

interface ILookup {
            public void someInterfaceMethod1();
            public void someInterfaceMethod2();
}
Run Code Online (Sandbox Code Playgroud)

......和实施类:

public class extendedLookUpImplementor: ILookup
{
          //constructor
          LookUpImplementor(){
          }

          public void someInterfaceMethod1(){
           // Implementation Code here.
          }

          public void someInterfaceMethod2(){
           // Implementation Code here.
          }

          public void ExtendedMethod(){
           // Implementation Code here.
          }

}
Run Code Online (Sandbox Code Playgroud)

在客户端代码中:

ILookup lookupVar = new LookUpImplementor();
lookupVar -> someInterfaceMethod1(); // i know it will work.
lookupVar -> someInterfaceMethod2(); // i know it will work.
Run Code Online (Sandbox Code Playgroud)

我的问题是,我可以使用lookupVar调用ExtendedMethod,如下所示:

lookupVar -> ExtendedMethod(); // Note again that ExtendedMethod() is not defined in Ilookup interface/contract.
Run Code Online (Sandbox Code Playgroud)

Ian*_*971 3

我认为只能通过将lookupVar强制转换为extendLookUpImplementor,或者通过反射。

  • 或者通过反射,或者使用“dynamic”,但是如果您有对派生类型的编译时引用,那么绝对可以选择强制转换。如果您没有编译时参考,那么也许可以考虑更改设计,并且仅在绝对必要时才采用反射/“动态”路线。 (2认同)