我一直在嘗試將正確的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