簡體   English   中英

C#中的類持久性

[英]Class persistence in C#

對於一個班級項目,我正在用C#創建一個RSS閱讀器。 我有為頻道,提要和文章構建的類。

我的主類MainView有一個List Channels,它將保存所有通道。

頻道只是保存提要的組織類。 (即“體育”,“技術”可能是渠道)。 渠道具有一個列表供稿,其中包含所有供稿。 因此,如果您有一個頻道“ Sports”,並且為ESPN創建了一個RSS feed,那么我將實例化一個Feed類。

但是,我不確定如何使MainView類中的Channels List在所有其他類中仍然存在。 當我想添加頻道時,我創建一個允許用戶輸入的彈出表單類(類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);這將添加到同一列表中,因為兩者變量引用相同的List。

例如,下面的演示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);
        }

}

補充閱讀

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM