【发布时间】:2011-11-26 23:01:52
【问题描述】:
我一直在尝试将正确的 OOP 原则应用于我的项目。我有一个名为 DocumentSection 的抽象类,以及从它派生的几个类(DocumentSectionView、DocumentSectionText 等)。同样,我有一个抽象类(DocAction),其中有几个派生自它的类(DocumentActionReplaceByTag、DocumentSectionAppend 等)。每个 DocumentSection 中都有一个 DocumentAction。
我对所有这些继承业务的理解是,通过指定一个“DocumentAction”,这将允许将任何派生类放在它的位置,并且基类的任何属性/方法也将可用正如我实例化的具体类中指定的任何内容。因此,在下面的示例中,我希望能够看到 PerformAction 方法(暂时将 virtual/override 关键字排除在外)。它是可用的。
但是,因为我使用了 v.DocAction = new DocumentActionReplaceByTag();,所以我还希望我的 ReplaceActionFindText 属性可见。
显然我在某处弄错了 - 任何 cmets 都表示赞赏。
class Program
{
static void Main(string[] args)
{
DocumentSectionView v = new DocumentSectionView();
v.DocAction = new DocumentActionReplaceByTag();
// would like to go:
//v.DocAction.ReplaceActionFindText...
Console.ReadLine();
}
}
public abstract class DocumentSection
{
public abstract string GetContent();
public DocumentAction DocAction { get; set; }
}
public class DocumentSectionView : DocumentSection
{
public string ViewPath { get; set; }
public dynamic ViewModel { get; set; }
public override string GetContent()
{
return "test";
}
}
public abstract class DocumentAction
{
void PerformAction(StringBuilder sb, string content);
}
public class DocumentActionReplaceByTag : DocumentAction
{
public string ReplaceActionFindText { get; set; }
public void PerformAction(StringBuilder sb, string content)
{
sb.Replace(ReplaceActionFindText, content);
}
}
编辑: 我已将答案标记为正确,但我想为以后遇到此问题的人添加我对此事的进一步思考的成果:
a) 正如所指出的,我的意图大体上是正确的,但我的方法是错误的。从 Main 方法设置“Action”属性不正确。在所有情况下,DocumentActionReplaceByTag 都需要 FindText,所以我将它放在构造函数中:
public DocumentActionReplaceByTag(string replaceActionFindText)
{
this.ReplaceActionFindText = replaceActionFindText;
}
从那时起,带有 0 个参数的构造函数将正确地失败,并防止执行操作但未指定 findtext 的情况。
b) 多态性现在可以正常工作,因为我的额外属性 findtext 已被填充,并且无论操作类型如何,运行 PerformAction 都会正确运行。
【问题讨论】:
-
谢谢大家。那么,在 DocumentSection 中指定可以指定任何类型的 DocAction 的“OOP 正确”方式是什么。目标是从我的旧方法(在stackoverflow.com/questions/8242520/… 讨论)转移到使用多态调用 action.GetContent();在我的 DocAction 上运行任何适当的 getcontent 操作。但要做到这一点,我需要设置特定于该操作的属性(如 ReplaceActionText)。下面的演员表被评论为不理想 - 演员表是唯一的方法吗?
标签: c# inheritance properties abstract-class