2012-01-27 11 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

静的イニシャライザにデータベース名の設定を追加する方がよいでしょうか? –

答えて

0

基本クラスは、一方向の継承である:基底クラスは、派生クラスのexistanceの知識を持たない、そしてそれはそれにアクセスすることはできません。

静的メソッドから非静的プロパティにアクセスするのに苦労するでしょう。

0

は、私が知っているあなたはすでにあなた自身の質問に答えましたが、いくつかの改善....

句は、継承を保証するところ、それは任意の静的メソッドは継承されたメソッドを使用することができることを意味します。継承されたクラスのインスタンスを作成できるようにする場合は、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; } 
} 
関連する問題