2012-03-13 19 views
2

何かを作成しようとしています。いくつかの基本クラスから派生したすべてのクラスは、ロード時に何らかの操作が実行されますが、プログラム。派生クラスを作る人が余分な作業をする必要がないようにしたいと思います。私の例では、子クラスが定義されているときに入力されたデリゲートを呼び出すOnInheritedAttribute()を作成しました。クラスで自動的に操作を実行し、一度だけ実行する方法

public class DelegateHolder 
{ 
    public bool Operation(Type t) { /*...*/ }; 
    static OnInheritedAttributeDelegate d = new OnInheritedAttributeDelegate(Operation); 
} 

[OnInheritedAttribute(DelegateHolder.d)] 
public abstract class AInheritable 
{ /*...*/ } 
//ideally, I could do this, and have the processing done 
public class SubClassA : AInheritable 
{ /*...*/ } 
//which would have the same effect as this, no attribute were assigned to AInheritable 
public class SubClassB : AInheritable 
{ 
    private static readonly bool _dummy = DelegateHolder.Operation(SubClassB); 
} 

私は第二の方法は、(アセンブリが複数回ロードされていない提供)私がやりたいだろう、ほぼ正だけど、呼び出すために必要なAInheritableのすべてのサブクラスを持つことが本当に迷惑だろうようにそれはそうこのコード。

別のオプションは、

public class BaseClass 
{ 
    static bool initialized; //this may not work, it will probably make one value for all classes rather than each subclass. 
    public BaseClass() 
    { 
    if(!/*System.Reflection code to get static member initialized from class of (this)*/) 
    { 
     /*perform registration*/ 
     /*System.Reflection code to get static member initialized from class of (this)*/ = true; 
    } 
    } 
} 

かもしれません。しかし多数のオブジェクトを作成しようとしている場合、これは不格好な、と無駄なようです。

これを合理化するためのアドバイスはありますか?

+2

これを理解してください - クラスのすべてのインスタンスで初期化コードを実行しますか?または、ロードされたすべてのタイプに対してコードを一度実行したいですか?いずれにしても、コンストラクタまたは静的コンストラクタのいずれかを探していますか? – Ani

+0

@ananthonline:彼は継承されている静的なイニシャライザを望んでいるようです。 – Guvante

+0

はい、私が望むものは、継承された静的初期化子と同等です。私はそれがまだ初期化されているかどうかを確認するために、すべての初期化ルーチンで余分なロジックを持つことを避けたいと思います。 –

答えて

3

静的プロパティが継承されないため、継承された静的イニシャライザが必要なように思えますが、これは直接動作しません。

ただし、ロジックを基本クラスのコンストラクタに追加するオプションがあります。いくつかのロジックを追加して複数の型を処理し、this.GetType()を使用して現在の型を取得します。例えば:

private static HashSet<Type> initializedTypes = new HashSet<Type>(); 
public BaseClass() 
{ 
    if (!initializedTypes.Contains(this.GetType()) 
    { 
     //Do something here 
     initializedTypes.Add(this.GetType()); 
    } 
} 
関連する問題