gpt4 book ai didi

c# - C# 中的类持久性

转载 作者:太空宇宙 更新时间:2023-11-03 13:45:09 25 4
gpt4 key购买 nike

对于一个类(class)项目,我正在用 C# 创建一个 RSS 阅读器。我有为 channel 、提要和文章构建的类。

我的主类 MainView 有一个包含所有 channel 的列表 channel 。

Channel 只是一个用于保存提要的组织类。 (即“体育”、“技术”可以是 channel )。 channel 有一个包含所有提要的提要列表。因此,如果您有一个 channel “体育”,并且为 ESPN 创建了一个 RSS 提要,那么我将实例化一个提要类。

但是,我不确定如何使 MainView 类中的 channel 列表在所有其他类中保持不变。当我想添加 channel 时,我创建了一个允许用户输入的弹出窗体类(类 addChannel)。但是为了访问 MainView 中的 Channels List,我必须将它传递给 addChannel 的构造函数,它只是正确地复制了 List?那么现在当我在addChannel类中操作列表时,我不是在修改原来的对吗?

我已经习惯了 C,我可以传递指针并直接在内存中修改原始变量。因此,在我继续让我的程序变得最糟糕之前,我想看看我这样做是否正确。

如果您希望我发布任何特定代码,请告诉我。

这段代码在我的 MainView 类中

 private void addBtn_Click(object sender, EventArgs e)
{

addChannel newChannel = new addChannel(channelTree, Channels);
newChannel.Show();

}

public List<Channel> Channels;

这段代码在addChannel类中

private void button1_Click(object sender, EventArgs e)
{


// I want to access the channelTree treeView here
channel = new Channel(this.channelTitle.Text, this.channelDesc.Text);

// Save the info to an XML doc
channel.Save();

// So here is where I want to add the channel to the List, but am not sure if it persists or not
channels.Add(channel);


// Now add it to the tree view
treeView.Nodes.Add(channel.Title);

this.Close();
}

最佳答案

假设您没有重置 MainView.Channels某个地方(例如 this.Channels = new List<Channels>;this.Channels = GetMeSomeChannels(); 然后当您调用 channels.Add(channel); 时,这是添加到同一个列表,因为两个变量引用同一个列表。

例如下面的demo通过 List<string>到另一个类(class)。然后另一个类将一个字符串添加到列表中。然后两个类都会观察到这个新字符串。

using System;
using System.Collections.Generic;

public class Test
{


public static void Main()
{
List<string> Channels = new List<string>() {"a","b", "c"};
AddChannel ac = new AddChannel(Channels);
ac.AddSomthing("foo");

foreach(var s in Channels)
{
Console.WriteLine(s);
}

}


}
public class AddChannel
{
private List<string> Channels {get;set;}
public AddChannel(List<string> Channels )
{
this.Channels = Channels ;
}

public void AddSomthing(string s)
{
this.Channels.Add(s);
}

}

补充阅读

关于c# - C# 中的类持久性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15606519/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com