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");
}
}
由於該方法不包含在接口中,因此需要將'refabc'強制轉換爲'Sample'。 – Ric