【问题标题】:How to avoid empty implementation in abstract class while implementing an interface?实现接口时如何避免抽象类中的空实现?
【发布时间】:2011-02-25 02:04:58
【问题描述】:
public interface IMyInterface
{
   int A { get; set; } 
   string S { get; set; } 
}

public abstract class MyAbs : IMyInterface
{ }

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

是否可以像上面那样在抽象类中省略空实现? 如果是这样,怎么做?为什么?

【问题讨论】:

  • 将代码放在代码段中
  • 如果你的抽象类完全没有实现,那为什么还要它呢?为什么不使用接口?抽象类通常用于您提供部分实现的情况。

标签: c#-2.0


【解决方案1】:

您可以在抽象类中将方法/属性定义为抽象,这样它就不会有空实现

你提供的代码不会编译

你需要的是

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

【讨论】:

【解决方案2】:

抽象类的目的是封装一些适用于所有派生类的常见行为。如果你的抽象类中什么都没有,那么没有任何目的,ConcreteClass 应该直接实现接口。

如果您随后添加了另一个同样实现此行为的类,那么如果有意义的话,就是重构和创建抽象基类的时候了。

【讨论】:

  • stackoverflow.com/questions/197893/… 请看一下这个链接
  • a) 那是 Java 而不是 C#,在 C# 中你必须将方法声明为抽象的,b) 它不会改变这样一个事实,即完全抽象的类在这种情况下没有用处
  • 不行,你必须实现方法或者声明它是抽象的
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-07-17
  • 2020-10-20
  • 2012-01-20
  • 1970-01-01
  • 2019-06-05
  • 1970-01-01
相关资源
最近更新 更多