2012-01-27 131 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; } 
} 
相关问题