C# 如何使用参数调用构造函数?

C# 如何使用参数调用构造函数?,c#,C#,我有两个类,我需要它们彼此创建实例。 为了防止堆栈溢出异常,我使用带参数的构造函数。但是我怎么称呼他们呢?我只能调用基本构造函数 public class TimerData : INotifyPropertyChanged { public TimerData() { //parameters = new Parameters(); } public TimerData(Parameters pr = null) { p

我有两个类,我需要它们彼此创建实例。 为了防止堆栈溢出异常,我使用带参数的构造函数。但是我怎么称呼他们呢?我只能调用基本构造函数

public class TimerData : INotifyPropertyChanged
{
    public TimerData()
    {
        //parameters = new Parameters();
    }

    public TimerData(Parameters pr = null)
    {
        parameters = pr ?? new Parameters(this);
    }

    // Here I create an instance of the TimerData class to call the constructor 
    // with parameters through it. It gives an error that the field initializer 
    // cannot access a non-static field
    TimerData timerData = new TimerData();
    private Parameters parameters = new Parameters(timerData);
}


public class Parameters : INotifyPropertyChanged
{
    public Parameters()
    {
        //timerData = new TimerData();
        //timerData.EventSecondsNotify += DecreaseFatigue;
        //timerData.EventSecondsNotify += DecreaseSatiety;
    }

    // How to call this constructor?
    public Parameters(TimerData td = null)
    {
        timerData = td ?? new TimerData(this);
        timerData.EventSecondsNotify += DecreaseFatigue;
        timerData.EventSecondsNotify += DecreaseSatiety;
    }

    private TimerData timerData;
}

我不明白为什么要在构造函数之外初始化实例。这应该很好:

public class TimerData
{
  private Parameters parameters;
  public TimerData(Parameters pr = null)
  {
    parameters = pr ?? new Parameters(this);
  }
}
public class Parameters
{
  private TimerData timerData;
  public Parameters(TimerData td = null)
  {
    timerData = td ?? new TimerData(this);
  }
}

我不明白为什么要在构造函数之外初始化实例。这应该很好:

public class TimerData
{
  private Parameters parameters;
  public TimerData(Parameters pr = null)
  {
    parameters = pr ?? new Parameters(this);
  }
}
public class Parameters
{
  private TimerData timerData;
  public Parameters(TimerData td = null)
  {
    timerData = td ?? new TimerData(this);
  }
}

我认为这是您的问题:“您不能使用一个实例变量来初始化另一个实例变量。为什么?因为编译器可以重新排列它们-不能保证timerData将在参数之前初始化,因此上面的一行可能会引发NullReferenceException。”你真的需要无参数的构造函数吗?即使你删除了已发布的行,这仍然是堆栈溢出, TimeDATAs//Cuff>无限地构造自己。考虑到为了避免参数Par具有一个DelalUT值的Cor,你有默认的无参数Ctoor,因为我认为这是你的问题:“不能使用实例变量初始化另一个实例变量。为什么?因为编译器可以重新排列这些参数,所以不能保证timerData会在参数之前初始化,所以上面的一行可能会抛出NullReferenceException。“您真的需要无参数的构造函数吗?即使删除了已发布的行,这仍然是堆栈溢出,<代码> TimeDATAs//Cuff>无限地构造自己。还考虑避免参数Par具有DealalTurt值的Cor,您有缺省的无参数Cor,谢谢!我只是忘记了当我有
参数(timerdatatd=null)
时,我不需要构造函数
参数()!我只是忘记了当我有
参数(timerdatatd=null)