【问题标题】:what is the behaviour abstract class and interface in c#? [duplicate]c#中的行为抽象类和接口是什么? [复制]
【发布时间】:2014-01-02 01:30:23
【问题描述】:

我在下面有代码

public interface NomiInterface
{
     void method();
}
public abstract class Nomi1
{
     public void method()
     {
     }
}
public class childe : Nomi1, NomiInterface 
{ 
}

现在编译成功了吗?为什么不需要重写子类中的接口方法?

【问题讨论】:

  • 你有没有注意到接口定义了一个名为mehtod的方法,而抽象类定义了method
  • 您是否尝试过新编辑的答案?因为它现在编译没有任何错误。你的问题是约翰桑德斯写的。
  • 您不需要再次实现它,因为子类已经从其父类 Nomi1 实现了“方法”方法。如果您想以其他方式实现它,请将 Nomi1 中的方法“方法”设为虚拟并在子类中覆盖它

标签: c# asp.net .net interface abstract-class


【解决方案1】:

你需要explicit implementation的接口。抽象类方法method()实现满足了实现接口抽象方法的需要。所以在类childe中定义接口的方法,但是显式实现需要调用接口的方法而不是类。

public interface NomiInterface
{
     void method();
}
public abstract class Nomi1
{
     public void method()
     {
          Console.WriteLine("abstract class method");
     }
}
public class childe : Nomi1, NomiInterface 
{ 
     void NomiInterface.method()
     {
          Console.WriteLine("interface method"); 
     }
}

您可以测试如何调用childe中存在的抽象类和接口实现的方法

childe c = new childe();
NomiInterface ni = new childe();
ni.method();
c.method();

输出是

interface method
abstract class method

另一方面,如果您不进行显式接口实现,则子类中给出的实现将不会调用子类或接口对象。

public interface NomiInterface
{
    void method();
}
public abstract class Nomi1
{
    public void method()
    {
        Console.WriteLine("abstract class method");
    }
}
public class childe : Nomi1, NomiInterface
{
    void method() { Console.WriteLine("interface method"); }
}

像以前一样创建类和接口的对象。

childe c = new childe();
NomiInterface ni = new childe();
ni.method();
c.method();

你会得到的输出

abstract class method
abstract class method

作为附加说明,您将注意类/方法名称的命名约定。您可以找到有关命名约定的更多信息here

【讨论】:

  • 问题是他在界面的mehtod中有错字。这个答案令人困惑。
  • @Kikaimaru - OP 询问实现的来源、抽象类以及为什么它没有被覆盖。 Adil 的回答解释了这一点。
  • @Tim 问题在我发表评论后被编辑。但我仍然不明白这个答案。答案是他不需要在孩子中实现它,因为父母已经实现了它并且它没有被覆盖,因为没有人覆盖它。显式接口实现没有任何帮助。
猜你喜欢
  • 2011-06-04
  • 2019-12-14
  • 2011-01-23
  • 2010-11-13
  • 2013-02-17
  • 2012-08-04
  • 2011-10-10
相关资源
最近更新 更多