链接构造函数不按预期更新变量

时间:2016-11-30 17:26:19

标签: c# .net

我创建了一个类似于下面的类。如您所见,我创建了一些构建器,我尝试使用: this()

进行链接
class RTTutils
{
    #region Variables

    private bool verbose = false;
    private bool canWrite = false;

    private int x;
    private int y;

    public RTTutils()
    {
        x = 5;

        y = 5;

        RTTCalc();
    }

    public RTTutils(int samples, bool verbose) : this()
    {
        this.verbose = verbose;
        this.samples = samples;
    }

    public RTTutils(int samples, bool verbose, bool canWrite) : this()
    {
        this.verbose = verbose;
        this.samples = samples;
        this.canWrite = canWrite;
    }

    public RTTutils(int samples) : this(samples, false, false)
    {
    }

    public RTTutils(bool verbose) : this()
    {
        this.verbose = verbose;
    }

    private void RTTCalc()
    {
        if (this.verbose)
            Console.WriteLine("Test");
    }

我正在尝试使用

初始化它
RTTutils rttcalculator = new RTTutils(true);

verbosecanWrite的任何其他组合,它们仍然是false。作为一个例子,在这种情况下,即使我在初始化类时指示true,我们也不会在控制台中看到任何内容。

在这种情况下,我做错了什么?

2 个答案:

答案 0 :(得分:0)

您希望(错误地)方法RTTCalc中使用的布尔类字段具有您在带有参数的构造函数中设置的值。但是,无参数构造函数在这些赋值之前执行。

不要在无参数构造函数中调用RTTCalc。改为提供静态工厂方法:

class RTTutils
{
    private bool verbose = false;
    private bool canWrite = false;

    private RTTutils()
    {
        sampleList.Add(100);    // First sample should be 100
        optionChosen.Add("E");

        x = 5;
        y = 5;

        System.IO.File.Delete(this.path);
    }

    private RTTutils(bool verbose) : this()
    {
        this.verbose = verbose;
    }

    private void RTTCalc()
    {
        if (this.verbose)
            Console.WriteLine("Test");
    }    

    public static RTTutils Create(bool verbose)
    {
      RTTutils result = new RTTutils(verbose);
      result.RTTCalc();
      return result;
    }
}

答案 1 :(得分:0)

鉴于上面的代码,我重新编写了它,并按预期初始化了详细信息和canWrite。

类Foo     {

    private bool _verbose = false;
    private bool _canWrite = false;
    private int _samples;
    private int x;
    private int y;


    public Foo(int samples, bool verbose, bool canWrite)
    {
        _verbose = verbose;
        _canWrite = canWrite;
        _samples = samples;
        x = 5;
        y = 5;

        RTTCalc();
    }
    public Foo() : this(0, false, false) { }

    public Foo(int samples) : this(samples, false, false) { }

    public Foo(int samples, bool verbose) : this(samples, verbose, false) { }


    private void RTTCalc()
    {
        Console.WriteLine($"V={_verbose}, S={_canWrite}");
        Console.ReadKey();
    }

}

class Program
{
    static void Main(string[] args)
    {
        Foo test1 = new Foo(1, true, false);
        Foo test2 = new Foo(1, true);
        Foo test3 = new Foo();

    }
}

这对你有用吗?如果没有,那么您正在做一些其他未在您的代码中显示的影响详细和canWrite的内容。