2012-01-27 134 views
0

這裏是什麼,我試圖完成一個樣本:如何從基類靜態方法訪問派生類的值?

public class BaseClass<T> 
{ 
    public static T GetByID(int ID) 
    { 
     // Need database name here that is determined at design time in the derived class. 
     var databaseName = ""; 
     // do some stuff involving database name that gets me object by ID here. 
     return default(T); 
    } 
} 
public class DerivedClass : BaseClass<DerivedClass> 
{ 
    private string DatabaseName { get; set; } 
} 

基本上,我會如何訪問派生「數據庫名」在基類的靜態GetByID方法?

編輯:當我發佈這個,我嘗試了一件事。我之前玩過屬性,但失敗了,但我認爲我的大腦很爛。只是再次嘗試,並進行測試,它正在工作。這是更新後的示例。

public class BaseClass<T> 
{ 
    public static T GetByID(int ID) 
    { 
     // Need database name here that is determined at design time in the derived class. 
     var databaseName = ((DatabaseAttribute)typeof(T).GetCustomAttributes(typeof(DatabaseAttribute), true).First()).DatabaseName; 
     // do some stuff involving database name that gets me object by ID here. 
     return default(T); 
    } 
} 
[Database("MyDatabase")] 
public class DerivedClass : BaseClass<DerivedClass> 
{ 

} 
public class DatabaseAttribute : Attribute 
{ 
    public DatabaseAttribute(string databaseName) 
    { 
     DatabaseName = databaseName; 
    } 
    public string DatabaseName { get; set; } 
} 
+0

將數據庫名稱設置放入靜態初始化程序不是更好嗎? – 2013-05-10 14:22:02

回答

0

基類派生類是單向繼承:基類沒有派生類中是否存在等方面的知識,所以它不能訪問它。

除此之外,您將很難從靜態方法訪問非靜態屬性。

0

我知道你已經回答了你自己的問題,但一些改進....

添加where子句來保證繼承,這意味着任何靜態方法可以利用繼承的方法。如果您希望能夠創建繼承類的實例,您可能還想添加new()子句。

public class BaseClass<T> : where T : BaseClass<T> 
{ 

    static readonly string databaseName; 


    static BaseClass() { 
     // Setup database name once per type of T by putting the initialization in 
     // the static constructor 

     databaseName = typeof(T).GetCustomAttributes(typeof(DatabaseAttribute),true) 
           .OfType<DatabaseAttribute>() 
           .Select(x => x.Name) 
           .FirstOrDefault(); 
    } 

    public static T GetByID(int ID) 
    { 
     // Database name will be in the static field databaseName, which is unique 
     // to each type of T 

     // do some stuff involving database name that gets me object by ID here. 
     return default(T); 
    } 
} 

[Database("MyDatabase")] 
public class DerivedClass : BaseClass<DerivedClass> 
{ 

} 

public class DatabaseAttribute : Attribute 
{ 
    public DatabaseAttribute(string databaseName) 
    { 
     DatabaseName = databaseName; 
    } 
    public string DatabaseName { get; set; } 
} 
相關問題