2015-06-22 44 views
0

我們有一個C#類,它爲MVC Web應用程序中的用戶保存會話值。現在我想讓這個類更通用。到現在爲止,我們有getter和setter像寄存器返回類型

public class WebAppLogin 
{ 
    public static WebAppLogin Current 
    { 
     get; //Gets the current Login from the session 
     set; //Sets the current Login to the session 
    } 
    public UserObject User 
    { 
     get; //Gets the value from the session 
     set; //Sets the value to the session 
    } 

    //Method for the UserObject 
    public List<String> GetUserRoles() 
    { 
     //kind of magic stuff 
     return userroles; 
    } 
} 

會話有了這個類,我們可以像這樣訪問

WebAppLogin.Current.User 

當前用戶對象我想要寫一個通用類,允許開發人員註冊用戶對象的類型並在他們的項目中使用這種類型的對象。

我的做法是這樣的

public class GenericLogin<T> 
{ 
    public static GenericLogin<T> Current 
    { 
     get; //Gets the current Login from the session 
     set; //Sets the current Login to the session 
    } 
    public T User 
    { 
     get; //Gets the value from the session 
     set; //Sets the value to the session 
    } 
} 

現在開發人員必須編寫User到處他們想使用它的類型。

我的問題是,有沒有一些圖案或庫(內置於.NET或免費用於商業用途),讓我在Application_Start註冊User的類型和使用這種類型的返回類型爲我User物業?

原因是這是我們非常嚴格的命名約定。 User對象幾乎總是實體類。我們最終會得到像

GenericLogin<ABC01_REGISTERED_USER>.Current.User; 

這是我想要防止的。有沒有解決方案?

回答

2

如果你知道在啓動類型,你可以只派生類:

public class UserLogin : GenericLogin<ABC01_REGISTERED_USER> 
{ } 

然後一直使用這個類。否則,每次都必須提供類型名稱,否則它不會知道每次都要使用該類型。

+0

謝謝,但是有沒有其他的可能性使用typeof? – JoeJoe87577

+0

不是。沒有別的東西會在編譯時強制輸入。 –