我正在使用实现类引用从接口(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/