c# - 调用接口(interface)实现的类方法

标签 c#

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

我无法在创建对象后调用已实现的类方法 从界面?

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

   }
}

最佳答案

您必须将 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(); 

旁注:看来,在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
      ...
    }
  }

关于c# - 调用接口(interface)实现的类方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33231286/

相关文章:

c# - EndPrint 事件 System.Drawing.Printing

c# - Serilog 不适用于 Reliable Actor Services

c# - Entity Framework 代码优先 : which DataType attribute for DateTime2?

c# - WPF中有没有类似于Visual Studio工具箱的控件?

c# - “System.Net.Http”已经具有为 'System.Runtime' 定义的依赖项

c# - 如何从 Azure Cloud Function 引用 "Portable".NET 程序集?

c# - 为指定用户打开 "Find shelvesets"页面

c# - "o"作为变量前缀是什么意思?

c# - 不同项目模板的一般错误处理消息

c# - 任何好的 C# SIP 库?