【问题标题】:Can I omit interface methods in abstract classes in C#?我可以在 C# 的抽象类中省略接口方法吗?
【发布时间】:2010-03-03 15:37:51
【问题描述】:

我是一名试图进入 C# 的 Java 开发人员,我正试图找到与一些 Java 代码相当的好方法。在 Java 中,我可以这样做:

public interface MyInterface
{
    public void theMethod();
}

public abstract class MyAbstractClass implements MyInterface
{
    /* No interface implementation, because it's abstract */
}

public class MyClass extends MyAbstractClass
{
    public void theMethod()
    {
        /* Implement missing interface methods in this class. */
    }
}

与此等效的 C# 是什么?使用抽象/新/覆盖等的最佳解决方案似乎都导致在抽象类中使用某种形式的主体声明“theMethod”。如何在不属于它的抽象类中删除对该方法的引用,同时在具体类中强制执行它?

【问题讨论】:

    标签: c# java class abstract-class


    【解决方案1】:

    你不能,你必须这样做:

    public interface MyInterface 
    { 
        void theMethod(); 
    } 
    
    public abstract class MyAbstractClass : MyInterface 
    { 
         public abstract void theMethod();
    } 
    
    public class MyClass : MyAbstractClass 
    { 
        public override void theMethod() 
        { 
            /* Implement missing interface methods in this class. */ 
        } 
    } 
    

    【讨论】:

      【解决方案2】:

      不,你必须在抽象类中仍然有方法签名,但在派生类中实现它。

      例如

      public interface MyInterface
      {
           void theMethod();
      }
      
      public abstract class MyAbstractClass: MyInterface
      {
           public abstract void theMethod();
      }
      
      public class MyClass: MyAbstractClass
      {
           public override void theMethod()
           {
                /* implementation */
           }
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-08-13
        • 1970-01-01
        相关资源
        最近更新 更多