如何从基类静态方法访问派生类值?

时间:2012-01-27 00:30:15

标签: c#-4.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方法中访问派生的“DatabaseName”?

编辑:发布此内容之后,我又尝试了一件事。我之前玩过属性,但失败了,但我认为我的大脑是糊状的。刚刚再次尝试并进行了测试,它正在运行。这是更新的样本。

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; }
}

2 个答案:

答案 0 :(得分:0)

派生类的基类是单向继承:基类不知道派生类的存在,因此无法访问它。

除此之外,您将很难从静态方法访问非静态属性。

答案 1 :(得分: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; }
}