2015-10-20 199 views
2

我從接口類創建對象與實現類的引用,但我的問題是我無法調用派生類使用對象的方法。調用接口實現的類方法

從接口創建對象 之後,我無法調用實現的類方法嗎?

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

    } 
} 
+0

由於該方法不包含在接口中,因此需要將'refabc'強制轉換爲'Sample'。 – Ric

回答

0

你要投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 

另一種方法是申報refabcSample例如:

// 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(); 

旁註:似乎,實施IabcDemo類是冗餘。我寧願這樣說:

// 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 
     ... 
    } 
    } 
+0

我正在使用依賴注入的第一種方法,但現在看起來像我的實現類不能有自己的方法,因爲在MVC中的控制器級別我不想透露實現類名稱。 – Coder

相關問題