这里是什么,我试图完成一个样本:如何从基类静态方法访问派生类的值?
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