我可以在C#中的抽象类中省略接口方法吗?

时间:2010-03-03 15:37:51

标签: c# java class abstract-class

我是一名Java开发人员,正试图进入C#,而我正试图找到一个与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#的等价物是什么?使用abstract / new / override等的最佳解决方案似乎都导致'theMethod'在抽象类中使用某种形式的主体声明。如何在不属于它的抽象类中删除对此方法的引用,同时在具体类中强制执行它?

2 个答案:

答案 0 :(得分:5)

你不能,你必须这样做:

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. */ 
    } 
} 

答案 1 :(得分:2)

不,你不得不在抽象类中使用方法签名,而是在派生类中实现它。

e.g。

public interface MyInterface
{
     void theMethod();
}

public abstract class MyAbstractClass: MyInterface
{
     public abstract void theMethod();
}

public class MyClass: MyAbstractClass
{
     public override void theMethod()
     {
          /* implementation */
     }
}