我有一个以下的应用程序:
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) }
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"); }
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实例的内容?
答案 0 :(得分:0)
如何直接在#3中更改#1实例的内容?
嗯,您首先将#1的实例传递给#3。目前你没有这样做。
例如:
public EditorForm(DataLayer_Json data)
{
...
}
和
using (var EF = new EditorForm(data))
然后在EditorForm
内,您可以执行任何操作data
(除以重新分配实际参考值),这些更改将反映在{{1}之外同样。
EditorForm