如何在c#构造类后立即调用方法?
问题描述:
我有一个叫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
属性是第一个被设置的?
答
即使虚拟方法在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
你会做它在属性''setter'公众的IList参数{保护得到;组; }' –
我会使用工厂模式。可能是抽象工厂模式,如果你有基类 – Liam
我喜欢工厂模式和模板方法模式.... –