调用接口实现的类方法
问题描述:
我从接口类创建对象与实现类的引用,但我的问题是我无法调用派生类使用对象的方法。调用接口实现的类方法
从接口创建对象 之后,我无法调用实现的类方法吗?
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();
旁注:似乎,实施Iabc
在Demo
类是冗余。我宁愿这样说:
// 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
由于该方法不包含在接口中,因此需要将'refabc'强制转换为'Sample'。 – Ric