开发者

How to avoid empty implementation in abstract class while implementing an interface?

public interface IMyInterface
{
   int A { get; set; } 
   strin开发者_StackOverflow中文版g S { get; set; } 
}

public abstract class MyAbs : IMyInterface
{ }

public class ConcreteClass : MyAbs
{
   /* Implementation of IMyInterface*/
}

Is it possible to omit the empty implementation in an abstract class as above? If so, how? why?


you can define the methods/properties as abstract in the abstract class so it won't have empty implementation

The code you provided will not compile

what you need is

    public interface IMyInterface
    {
        int A
        { get; set; }
        string S
        { get; set; }
    }
    public abstract class MyAbs : IMyInterface
    {
        public abstract int A { get; set; }
        public abstract string S { get; set; }
    }
    public class ConcreteClass : MyAbs
    {
        /* Implementation of IMyInterface*/
    }


The purpose of an abstract class is to encapsulate some common behaviour that applies to all the deriving classes. If you haven't got anything at all in your abstract class then it there is no purpose to having it, ConcreteClass should implement the interface directly.

If you subsequently add another class that also implements this behaviour, then that is the time to refactor and create an abstract base class if it makes sense.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜