解决此循环引用的最有效方法?

Most efficient way to solve this circular reference?

这里是 C# 的新手。所以我在不同的项目中得到了我的第一个 class (Form1) 和第二个 class (Class1)。我将 Form1 添加到 Class1 的引用中,因为 Form1 具有来自其 GUI 的数据,Class1 需要通过其方法进行计算。问题是,我无法从 Class1 中的方法获取结果到 Form1,因为由于循环引用我无法引用它。

public partial class Form1 : Form 
{

    public Form1()
    {
        InitializeComponent();

    }

    private void label3_Click(object sender, EventArgs e)
    {

    }

    public void button1_Click(object sender, EventArgs e)
    {
       // for getting data from Class1
       // ClassLibrary1.Class1 c = new ClassLibrary1.Class1();
       // label7.Text = c.GetDate();        }

    private void button2_Click(object sender, EventArgs e)
    {

    }
}



 public class Class1
 {

    private int daysz;

    private int GetDate()
    {
        Activity3_Espiritu.Form1 f = new Activity3_Espiritu.Form1();
        daysz = (f.lastDay - f.firstDay).Days;
        return daysz;
    }

}

有什么干净的方法可以解决这个问题?我尝试过界面,但我完全不知道如何使用它,甚至在网上寻找解决方案之后也是如此。

如果您可以更改 GetDate 方法的签名,您可以尝试此代码:

public class Class1
{
  private int daysz;

  private int GetDate(__yourDatType__ lastDay, __yourDatType__ firstDay)
  {
    daysz = (lastDay - firstDay).Days;
    return daysz;
  }
}

现在,在button1_Click中写下:

ClassLibrary1.Class1 c = new ClassLibrary1.Class1();
label7.Text = c.GetDate(this.lastDay, this.firstDay);

Class1 永远不需要对您的 Form1 的引用,而来自 Form1 的代码应该调用 Class1 中的 GetDate() 方法并传入适当的参数以供 GetDate() 进行计算。当 GetDate() returns 结果时,您只需将其分配给一个变量或返回到需要显示它的用户控件(会是 Label7 吗?)。

public void button1_Click(object sender, EventArgs e)
{
    var c = new Class1();
    var yourResult = c.GetDate(lastDay, firstDay);
    label7.Text = yourResult;
}

public int GetDate(DateTime lastDate, DateTime firstDate)
{
    return (lastDate - firstDate).Days;
}