【问题标题】:Most efficient way to solve this circular reference?解决此循环引用的最有效方法?
【发布时间】:2017-09-09 12:52:10
【问题描述】:

这里是 C# 新手。所以我在不同的项目中得到了我的第一堂课(Form1)和第二堂课(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;
    }

}

解决这个问题的干净方法是什么?我已经尝试过接口,但我完全不知道如何使用它,即使在网上寻找解决方案后也是如此。

【问题讨论】:

  • 我不确定这对这个网站是否是一个好问题(下次最好尝试programmers.stackexchange.com),但避免这种形式的循环引用的通常方法是引入一种新类型这两种旧类型都引用了。
  • 将必要的数据传递给 class1 并返回结果。不要在 class1 中引用 form1
  • lastDayfirstDay 声明在哪里?它们不在表格或 Class1 中。如果它们在表单中,那么您根本不需要 Class1 来计算日期范围的长度,您只需将长度传递给 Class1(如果您想将其存储在那里)

标签: c# oop visual-studio-2013 circular-dependency


【解决方案1】:

Class1 永远不需要对您的 Form1 的引用,而是来自 Form1 的代码应该调用 Class1 中的 GetDate() 方法并传入适当的参数以供 GetDate() 评估。当GetDate() 返回结果时,您只需将其分配给一个变量或返回到需要显示它的用户控件(是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;
}

【讨论】:

    【解决方案2】:

    如果您可以更改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);
    

    【讨论】:

      猜你喜欢
      • 2021-03-17
      • 1970-01-01
      • 2011-02-13
      • 1970-01-01
      • 2018-03-11
      • 2023-03-25
      • 1970-01-01
      • 2021-06-11
      • 1970-01-01
      相关资源
      最近更新 更多