繁体   English   中英

调用接口实现的类方法

[英]Calling interface Implemented class methods

我正在使用实现类引用从接口类创建对象,但是我的问题是我无法使用对象调用派生类的方法。

从接口创建对象后,我无法调用实现的类方法吗?

class Demo : Iabc
{
  public static void Main()
  {
     System.Console.WriteLine("Hello Interfaces");
     Iabc refabc = new Demo();
     refabc.xyz();
     Iabc refabc = new Sample();
     refabc.xyz();  
     refabc.Calculate(); // not allowed to call Sample's own methods     
   }

  public void xyz()
  {
      System.Console.WriteLine("In Demo :: xyz");
  }  
}

interface Iabc
{
      void xyz();
}

class Sample : Iabc
{
   public void xyz()
   {
       System.Console.WriteLine("In Sample :: xyz");
   }  
   public void Calculate(){
       System.Console.WriteLine("In Sample :: Calculation done");

   }
}

您必须将refabcSample

  // refabc is treated as "Iabc" interface
  Iabc refabc = new Sample();
  // so all you can call directly are "Iabc" methods
  refabc.xyz();  

  // If you want to call a methods that's beyond "Iabc" you have to cast:
  (refabc as Sample).Calculate(); // not allowed to call Sample's own methods  

另一种方法是将refabc声明为Sample实例:

  // refabc is treated as "Sample" class
  Sample refabc = new Sample();
  // so you can call directly "Iabc" methods ("Sample" implements "Iabc")
  refabc.xyz();  

  // ...and "Sample" methods as well
  refabc.Calculate(); 

旁注 :似乎在Demo类中实现Iabc多余的 我宁愿这样说:

  // Main method is the only purpose of Demo class
  static class Demo  { // <- static: you don't want to create Demo instances
    public static void Main() { 
      // Your code here
      ...
    }
  }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM