我有一個叫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
屬性是第一個被設置的?
你會做它在屬性''setter'公衆的IList參數{保護得到;組; }' –
我會使用工廠模式。可能是抽象工廠模式,如果你有基類 – Liam
我喜歡工廠模式和模板方法模式.... –