在c#中构造类后,如何立即调用方法?

时间:2016-08-05 15:09:24

标签: c# class oop

我有一个名为ReportFunction的抽象类。它有一个默认的构造函数,它应该在构造之后始终调用方法ValidateAndSetParameters()

这是我的抽象类

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");

在构造类并设置了Parameters属性之后,我希望或需要调用方法ValidateAndSetParameters() 。但似乎正在发生的事情是在初始化之前调用ValidateAndSetParameters()。或者由于某些原因Parameters在初始化期间未设置。

如何确保在构造类并首先设置ValidateAndSetParameters()属性后调用方法Parameters

1 个答案:

答案 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

所以不是覆盖那个方法,而是可以使用本地方法或只是在ctor中放置验证并删除覆盖ValidateAndSetParameters