调用接口已实现的类方法

时间:2015-10-20 08:08:14

标签: c#

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

创建对象后,我无法调用实现的类方法  来自界面?

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");

   }
}

1 个答案:

答案 0 :(得分:0)

您必须将#EXTM3U #EXT-X-VERSION:6 #EXT-X-STREAM-INF:PROGRAM-ID=1,BANDWIDTH=2855600,CODECS="avc1.4d001f,mp4a.40.2",RESOLUTION=960x540 medium.m3u8 #EXT-X-STREAM-INF:PROGRAM-ID=1,BANDWIDTH=5605600,CODECS="avc1.640028,mp4a.40.2",RESOLUTION=1280x720 high.m3u8 #EXT-X-STREAM-INF:PROGRAM-ID=1,BANDWIDTH=1755600,CODECS="avc1.42001f,mp4a.40.2",RESOLUTION=640x360 low.m3u8 投射到refabc

Sample

另一种方法是将 // 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(); 类中实施Iabc 冗余。我宁愿这样说:

Demo