2016-08-05 67 views
1

我有一個叫ReportFunction的抽象類。它有一個默認構造函數,它應該在構造完成後始終調用方法ValidateAndSetParameters()如何在c#構造類後立即調用方法?

這裏是我的抽象類

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

} 

我完成ReportFunction類具有以下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(); 
    } 

} 

我初始化Replace類兩種方法之一

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(new ReportFilter("something to search in"), "something to search for", "Something to replace with"); 

我希望或需要調用類的構造ValidateAndSetParameters()後的方法和參數屬性設置。但似乎發生的是在初始化之前調用ValidateAndSetParameters()。或者由於某種原因,Parameters在初始化期間沒有被設置。

如何確保方法ValidateAndSetParameters()在構建類之後調用並且Parameters屬性是第一個被設置的?

+0

你會做它在屬性''setter'公衆的IList 參數{保護得到;組; }' –

+0

我會使用工廠模式。可能是抽象工廠模式,如果你有基類 – Liam

+0

我喜歡工廠模式和模板方法模式.... –

回答

2

即使虛擬方法在ctor之前先被調用兩次,然後再從ctor內部調用,你的第二個變體也應該可以工作。

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

爲什麼被稱爲兩次? Do not call overridable methods in constructors

所以不是重寫這個方法,你可以使用本地方法或只是把驗證的構造函數,並刪除被覆蓋的ValidateAndSetParameters

相關問題