修改多个类层中的对象

时间:2016-08-31 23:37:01

标签: c# pointers reference pass-by-reference

我有一个以下的应用程序:

  1. 包含数据处理逻辑和数据本身的数据层类。
  2. public class DataLayer_JSON
    {
        CacheData chd = new CacheData();
        //The chd object contains the actual data used in the DataLayer_JSON class
    
       public DataLayer_JSON(string relPath) }
    
    1. 主菜单表单(基本上可以是任何类)
    2.  public partial class MainMenuForm : Form
      {
          DataLayer_JSON data = new DataLayer_JSON("questions.txt");
          ...
          private void btnEditon_Click(object sender, EventArgs e)
          {
          ...
              using (var EF = new EditorForm(data.GetCathegories(), data.GetDifficulties(), data.GetQuestions()))
              {
                  var result = EF.ShowDialog();
                  if(result == DialogResult.OK)
                  {
                      data.ClearQuestions();  //Clear all cached questions
                      //Since we are still in scope of the EditorForm (EF) within the using clause, we can access it's members
                      data.AddQuestionRange(EF.AllQuestions); //Replace cache with the edited list
                  }
              }
              ...
               //Here we save the data permanently to a text file when closing the program. 
               //This could also be done from the EditorForm if we wanted to
               private void MainMenuForm_FormClosing(object sender, FormClosingEventArgs e)
          {
              data.Save("questions.txt");
          }
      
      1. 编辑表格(从#2开始)
      2.   

        public EditorForm(IEnumerable<INameObject> Cathegories, IEnumerable<INameObject> Difficulties, IEnumerable<Question> oldQuestions) { ... }

        在#2中,我创建并初始化数据层实例(#1)。我想从#3中修改#1中包含的数据,但到目前为止,我只能通过#2将#1到#3的内容传递给值。结果然后从#3返回到#2并在那里处理。

        我已经读过在C#中通过引用传递,但我的结论是你不能为引用分配一个变量,然后让该变量修改原始数据。

        这次我在以下几个地方读到了C#中的引用,以及之前多次广泛阅读过这个主题: C# reference assignment operator? How do I assign by "reference" to a class field in c#?

        所以问题是: 如何直接在#3中更改#1实例的内容?

1 个答案:

答案 0 :(得分:0)

  

如何直接在#3中更改#1实例的内容?

嗯,您首先将#1的实例传递给#3。目前你没有这样做。

例如:

public EditorForm(DataLayer_Json data)
{
    ...
}

using (var EF = new EditorForm(data))

然后在EditorForm内,您可以执行任何操作data以重新分配实际参考值),这些更改将反映在{{1}之外同样。

EditorForm