c#中的类持久化

本文关键字:持久化 | 更新日期: 2023-09-27 18:05:53

对于一个课程项目,我正在用c#创建一个RSS阅读器。我已经为频道、提要和文章构建了类。

我的主类MainView有一个List Channels来保存所有的channel。

Channel只是一个保存提要的组织类。(比如"体育"、"科技"可以是频道)。Channel有一个List提要,其中包含所有提要。因此,如果您有一个频道"Sports",并且您为ESPN创建了一个RSS提要,那么我将实例化一个feed类。

然而,我不确定如何在MainView类中使我的Channels List跨所有其他类持续存在。当我想添加一个通道时,我创建一个允许用户输入的弹出式表单类(类addChannel)。但是为了在MainView中访问通道列表,我必须将其传递给addChannel的构造函数它只是复制列表,对吗?当我在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();
        }

c#中的类持久化

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

例如,下面的演示将List<string>传递给另一个类。然后,另一个类将向列表中添加一个字符串。然后两个类都观察到这个新字符串。

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);
        }
}

补充阅读资料

  • Jon Skeet在c#中传递参数