2016-08-05 11 views
1

私はReportFunctionという抽象クラスを持っています。それは構築された後に常にメソッドValidateAndSetParameters()を呼び出すべきであるデフォルトのコンストラクタを持っています。ここでクラスがC#で構築された後、メソッドを即座に呼び出す方法はありますか?

は私の抽象クラスは、私は私がReplaceクラス1〜2における方法

new Replace 
{ 
    Parameters = new List<IReportFilter> 
    { 
     new ReportFilter("something to search in"), 
     new ReportFilter("something to search for"), 
     new ReportFilter("Something to replace with"), 
    } 
}; 

などを初期化し、次のReplaceクラス

public class Replace : ReportFunction 
{ 
    public override void ValidateAndSetParameters() 
    { 
     if (this.Parameters != null && this.Parameters.Count() == 3) 
     { 
      foreach (var parameter in this.Parameters) 
      { 
       if (parameter.ReportColumn == null) 
       { 
        //Since this is a string function, the filter values should be text, force the filter type to SqlDbType.NVarChar which is the max allowed characters to replace using Replace function 
        parameter.Type = SqlDbType.NVarChar; 
       } 
       this.ValidParameter.Add(parameter); 
      } 
     } 
    } 

    public Replace() :base() 
    { 
    } 

    public Replace(IReportFilter stringExpression, string stringPattern, string stringReplacement) 
    { 
     this.Parameters = new List<IReportFilter> 
     { 
      stringExpression, 
      new ReportFilter(stringPattern), 
      new ReportFilter(stringReplacement) 
     }; 

     this.ValidateAndSetParameters(); 
    } 

} 

ReportFunctionクラスを完了し

public abstract class ReportFunction 
{ 

    public IList<IReportFilter> Parameters { protected get; set; } 
    public ICollection<IReportFilter> ValidParameter { get; protected set; } 

    /**** 
    * 
    * This method should validate parameters if any exists. 
    * Then it should add valid parameters to the 'ValidParameter' list 
    * 
    */ 
    public virtual void ValidateAndSetParameters() 
    { 
     this.ValidParameter = new Collection<IReportFilter>(); 
    } 

    .... I removed irrelevant methods for the sake of simplicity 

    public ReportFunction() 
    { 
     this.ValidateAndSetParameters(); 
    } 

} 

ですこの

Replace(new ReportFilter("something to search in"), "something to search for", "Something to replace with"); 

私は期待していたり​​、クラスが構築され、パラメータのプロパティが設定されている後方法ValidateAndSetParameters()を呼び出す必要があります。しかし、起きているように見えるのは、ValidateAndSetParameters()が初期化の前に呼び出されているということです。または何らかの理由でParametersが初期化中に設定されていません。

クラスが呼び出され、クラスが作成され、Parametersプロパティが最初に設定されていることを確認するにはどうすればよいですか?

+0

を削除することができます取得する;セット; } ' –

+0

私は工場のパターンを使います。おそらく抽象的な工場パターン – Liam

+0

私は工場パターンとテンプレートメソッドパターンの両方が好きです。 –

答えて

2

仮想メソッドがctorの前に2回、ctorの中から2回呼び出されても、2番目の方法が一般的に機能するはずです。

var replace= new Replace(new ReportFilter("something to search in"), "something to search for", "Something to replace with"); 

なぜ2回呼び出されますか? Do not call overridable methods in constructors

ので、代わりにそのメソッドをオーバーライドしますが、あなたは `公共のIList パラメータ{保護のプロパティ` setter`でそれを行うだろうCTORにローカル方法か、単に置く検証を使用してオーバーライドValidateAndSetParameters

関連する問題