這裏是什麼,我試圖完成一個樣本:如何從基類靜態方法訪問派生類的值?
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; }
}
將數據庫名稱設置放入靜態初始化程序不是更好嗎? – 2013-05-10 14:22:02