【问题标题】:How to merge two classes [closed]如何合并两个类[关闭]
【发布时间】:2015-02-08 14:57:43
【问题描述】:

在我的项目中,我有两个类:文章和新闻。它们中的某些字段是相同的。例如:标题、文本、关键字、MemberID、日期。

我创建了一个界面并在其中放置了相同的字段。对吗?

interface ITextContext
{
    public int ID { get; set; }
    public int Title { get; set; }
    public string Text { get; set; }
    public DateTime Date { get; set; }
    List<Keyword> Keywords;

}

public class Article:ITextContext
{
    public int ArticleID { get; set; }
    public bool IsReady { get; set; }
}

public class NewsArchive:ITextContext
{
    public int NewsArchiveID { get; set; }
}

【问题讨论】:

  • base class 在这里可能更合适,除非ArchiveNewsArchive 类之间的成员行为不同
  • 部分正确,您需要在每个类中实现这些接口成员。接口更像是对其余代码的说明,类将包含接口中定义的成员。
  • 如果将 iterface 更改为 Base Class 是否正确?
  • 你尝试构建这个吗?因为它不会建立。先试试吧!
  • 当然。这是 OO 的基本原则,如果您从接口继承,您应该实现它或使您的类抽象。你不需要接口,你需要一个基类。

标签: c# oop


【解决方案1】:

在当前的实现中,ITextContext 中定义的属性必须在ArticleNewsArchive 中实际实现才能编译。这将是有效的,但不会导致代码重用,另一方面,这不是接口的目的。

【讨论】:

  • 如果使用基类代替接口,是不是基于设计原则和oo?
  • 这有待讨论,无法明确回答。一方面,接口不能共享实现。另一方面,代码重用并不是继承的主要目的。在我看来,通过基类共享实现是可能且有效的。
  • 好的!感谢您的帮助。
【解决方案2】:

如果您只需要共享事件、索引器、方法和属性而不需要实现,您应该使用接口。

如果你需要共享一些实现,你可以像使用接口一样使用抽象类(抽象类不能被实例化)

public abstract class TextContext
{
    public int ID { get; set; }
    public int Title { get; set; }
    public string Text { get; set; }
    public DateTime Date { get; set; }
    List<Keyword> Keywords;

   public int PlusOne(int a){
       return a+1;
   }

}

public class Article:TextContext
{
    public int ArticleID { get; set; }
    public bool IsReady { get; set; }
}

public class NewsArchive:TextContext
{
    public int NewsArchiveID { get; set; }
}

现在,当您初始化新的ArticleNewsArchive 时,您会看到基类的字段、方法..。

【讨论】:

    【解决方案3】:

    没关系,假设您不想在类之间共享任何实现细节。例如,如果您想向 TextContext 添加一个可供 Article 和 NewsArchive 使用的方法,您可能希望从一个公共基类继承:

    public class TextContext
    {
        public int ID { get; set; }
        public int Title { get; set; }
        public string Text { get; set; }
        public DateTime Date { get; set; }
        List<Keyword> Keywords;    
    
        public string SomeMethod()
        {
            return string.Format("{0}\r\n{1}", Title, Text);
        }
    }
    
    public class Article : TextContext
    {
       ...
    }
    

    【讨论】:

    • 我认为如果将 SomeMethod() 更改为 Virtcual 会更好。不是吗?
    • 如果你希望能够覆盖 SomeMethod() 的实现,是的。
    • 感谢您的帮助。我将接口更改为基类。
    猜你喜欢
    • 2016-06-15
    • 2020-07-08
    • 1970-01-01
    • 2013-11-11
    • 2014-07-21
    • 2019-06-14
    • 2014-06-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多