简体   繁体   English

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

[英]Can I omit interface methods in abstract classes in C#?

I'm a Java developer who's trying to move into C#, and I'm trying to find a nice equivalent to some Java code. 我是一名Java开发人员,正在尝试使用C#,并且试图找到与某些Java代码等效的方法。 In Java, I can do this: 在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. */
    }
}

What would be a C# equivalent to this? 相当于C#的是什么? The best solutions using abstract/new/override etc all seem to result in 'theMethod' being declared with a body of some form or another in the abstract class. 使用abstract / new / override等的最佳解决方案似乎都导致'theMethod'在抽象类中以某种形式的主体或另一种形式的主体进行声明。 How can I go about removing reference to this method in the abstract class where it doesn't belong, whilst enforcing it's implementation in the concrete class? 如何在不属于该抽象类的抽象类中删除对该方法的引用,同时在具体类中强制实现该方法呢?

You cannot, you would have to do it like this: 您不能,您必须这样做:

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

No you would have to still have the method signature in the abstract class, but implement it in the derived class. 不,您仍然必须在抽象类中具有方法签名,但必须在派生类中实现它。

eg 例如

public interface MyInterface
{
     void theMethod();
}

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM