2009-12-14 62 views
4

我想在提取方法中提取出此處的常見代碼模式,但無法找到Presenter類型的正確類型。任何幫助?如何在此處提取代碼重複?

public bool CanGotoHome 
{ 
    get { return !(CurrentPresenter is IHomePresenter) && IsLoggedIn; } 
} 
public bool CanGotoImportanceOfAimsAndObjectives 
{ 
    get { return !(CurrentPresenter is IImportanceOfAimsAndObjectivesPresenter) && IsLoggedIn; } 
} 
public bool CanGotoGotoAimsAndObjectives 
{ 
    get { return !(CurrentPresenter is IAimsAndObjectivesPresenter) && IsLoggedIn; } 
} 
+0

btw,我會先檢查IsLoggedIn,然後才檢查類型。 – abatishchev 2009-12-14 05:26:24

回答

13

使用泛型

private bool SomeFuncName<T>() 
{ 
    return !(CurrentPresenter is T) && IsLoggedIn; 
} 

用法:

public bool CanGotoGotoAimsAndObjectives { 
    get { return SomeFuncName<IAimsAndObjectivesPresenter>(); } 
} 
+1

在這種情況下,一個好的函數名稱是CanGoTo,這會導致返回CanGoTo (); – 2009-12-14 03:05:53

+0

@Luke,感謝語法幫助,@Darko,方法名稱的好主意。 :) – 2009-12-14 03:24:33

+0

沒有probs。 另一個說明,你不喜歡隨機downvotes? – 2009-12-17 02:41:49

1

這段代碼看起來很奇怪,一般...如果只有那些3行,爲什麼還要建立一個通用的方法重構他們?這不會爲你節省很多重複。

OTOH,如果還有更多,那麼這個代碼看起來像典型的能力/權限查詢。如果你有三種以上的類型,那麼在其他情況下這些函數可能會變得更加複雜,那麼爲什麼不把它們加載到presenter_capabilities數據庫表(或者如果你在一個企業系統中,那麼甚至是AD)呢?檢查「基於能力的安全性」是否不是您真正需要的。

至於代碼本身,我會去這樣的事情:

public bool GetCapability(Caps cap) { 
    return IsLoggedIn && CapabilityResolver.Check(CurrentPresenter, cap); 
    // or even 
    // return CapabilityResolver.Check(CurrentPresenter, cap, IsLoggedIn); 
} 

// usage 
whatever.GetCapability(Caps.CanGoHome); 

節省你重新編譯如果規則變得更加複雜,或者如果添加任何新帽/接口。如果它們幾乎是靜態的,你可以通過一些散列來解決它們。

+0

感謝您的兩分錢,我會反思一下。 – 2009-12-14 03:25:08

1

基於代碼示例中,我會有點動心在這裏使用內置的主/角色定義,以及一些字符串常量:

static bool IsInRole(string role) { 
    if (string.IsNullOrEmpty(role)) return true; 
    IPrincipal principal = Thread.CurrentPrincipal; 
    return principal == null ? false : principal.IsInRole(role); 
} 
public bool CanGotoHome 
    get { IsInRole(AccessRights.GotoHome); } 
} 

雖然也許這只是轉移有責任創造一個合適的定製本人...

2

對我來說,如果對象只是知道它應該如何行動似乎更容易。

class BasePresenter 
{ 
    public bool CanGotoHome 
    { 
     get { return IsLoggedIn; } 
    } 
} 

class HomePresenter : BasePresenter 
{ 
    public bool CanGotoHome 
    { 
     get { return False; } 
    } 
} 

然後對其他方法也一樣。這似乎更簡單和更清晰。