我一直在尝试将正确的OOP原则应用于我的项目。我有一个名为DocumentSection的抽象类,以及从它派生的几个类(DocumentSectionView,DocumentSectionText等)。同样,我有一个抽象类(DocAction),它有几个派生自它的类(DocumentActionReplaceByTag,DocumentSectionAppend等)。每个DocumentSection都有一个DocumentAction。派生类中属性的可见性(C#)
我对所有这些继承业务的理解是,通过指定一个'DocumentAction',这将允许任何这些派生类放在它的位置,并且基类中的任何属性/方法都可用,例如以及我在实例化的具体类中指定的任何东西。因此,在下面的例子中,我希望能够看到PerformAction方法(现在将虚拟/覆盖关键字留在混合中)。它是可用的。然而,因为我去了v.DocAction = new DocumentActionReplaceByTag(),所以我还希望我的ReplaceActionFindText属性可见。
很明显,我错了某处 - 任何意见赞赏。
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);
}
}
编辑: 我标志着一个答案是正确的,但想到我会加上我进一步思考的成果,在这个问题上对那些跨稍后即将到来:
一)正如指出的,我的意图是大致正确的,但我的方法是错误的。从Main方法设置Action的属性是不正确的。在所有情况下,AA DocumentActionReplaceByTag需要FINDTEXT,所以我把它在构造函数中:
public DocumentActionReplaceByTag(string replaceActionFindText)
{
this.ReplaceActionFindText = replaceActionFindText;
}
从此,0参数的构造函数会正确地失败,并防止在执行该操作的情况下,但没有FINDTEXT是指定。
b)多态现在工作正常,因为我的额外属性findtext已填充,并且运行PerformAction将正确运行,无论操作类型如何。
谢谢大家。那么,在DocumentSection中指定任何类型的DocAction都可以指定的'OOP正确'方式是什么。我们的目标是从我的旧方法(在http://stackoverflow.com/questions/8242520/correct-oop-practice-for-class-properties-tied-by-logic讨论)移动到使用多态调用action.GetContent ();在我的DocAction上运行任何适当的getcontent动作。但要做到这一点,我需要设置特定于该操作的属性(如ReplaceActionText)。下面的演员被评论为不理想 - 正在铸造唯一的方法? – Glinkot