2012-03-14 49 views
3

我正在使用C#4.0中的項目。我有幾個演示者類,它們都從相同的基類繼承。這些演示者類中的每一個都有一個「當前」對象,這是每個演示者特有的,但它們也都有一個共同的繼承類,當然,與演示者分開。Casting派生類型和動態最佳實踐

在可怕的僞代碼:

class ApplicationPresenter inherits BasePresenter 
    Pubilc PersonApplication Current (inherited from Person) 
class RecordPresenter inherits BasePresenter 
    Public PersonRecord Current (inherited from Person) 
class InquiryPresenter inherits BasePresenter 
    Public PersonInquiry Current (inherited from Person) 

...等

有沒有辦法讓它這樣我就可以稱之爲「當前」從任何一個,而無需類型檢測,但使其符合最佳實踐?

我認爲最好的選擇是讓它變成動態的,因爲我知道我傳遞給它的任何東西都會有「當前」並且這樣做。這是正確的嗎?

或者是有,我可以創造一個辦法:適當

class BasePresenter 
    Public Person Current 

並作出投?

我知道有這方面的方法,但我一直在尋找乾淨和適當的方法。

謝謝!

回答

5

泛型類型參數添加到基本主持人,因此任何派生具體的主持人將能夠指定自定義當前項目類型:

public abstract class PresenterBase<TItem> 
{ 
    public TItem Current { get; private set; } 
} 

// now Current will be of PersonApplication type 
public sealed class ApplicationPresenter : PresenterBase<PersonApplication> 
{ 
} 

// now Current will be of PersonRecord type 
public sealed class RecordPresenter : PresenterBase<PersonRecord> 
{ 
} 
+0

這是非常好的。非常感謝! – 2012-03-14 14:43:49

+0

如果我想更改派生類中的get/set訪問器,對於事件跟蹤等實例,我該怎麼做? – 2012-03-14 14:59:36

+0

此外,我很愚蠢。我只是創建了一個名稱和類型相同的「新」方法,並且調用base.Current。 。 。對? – 2012-03-14 15:07:54