2013-03-25 46 views
2

。我为渠道,供稿和文章构建了课程。在C#中的类持久化对我在一个C#中创建一个RSS阅读器的类项目,我#

我的主类MainView有一个列表通道,可以容纳所有的通道。

渠道只是一个组织类来容纳饲料。 (即“体育”,“技术”可能是渠道)。一个频道有一个列表feed,用于保存所有的提要。所以如果你有一个频道,“体育”,并且你为ESPN创建了一个RSS feed,那么我将实例化一个Feed类。

但是,我不知道如何使MainView类中的通道列表在所有其他类中保持不变。当我想添加一个频道时,我创建了一个允许用户输入的弹出窗体类(class addChannel)。但为了访问MainView中的通道列表,我必须将它传递给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(); 
     } 
+0

*我不修改原吧?*无YOUE可能*正在修改*原始列表。这就是参考类型的意义。没有人能够看到你的构造函数以及你怎么称呼它。 – 2013-03-25 02:05:38

+0

因此,将原始频道列表发送到构造函数中时将自动通过引用而不是按值传递? – 2013-03-25 02:07:22

+2

我希望你没有通过引用和价值来表达,因为这里有很多混淆。但是,是的。乔恩Skeet有一个[好文章](http://www.yoda.arachsys.com/csharp/parameters.html)它的真正含义 – 2013-03-25 02:08:16

回答

1

假设你不进行重置MainView.Channels某个地方(如this.Channels = new List<Channels>;this.Channels = GetMeSomeChannels();那么当你打电话channels.Add(channel);这是添加到相同的列表,因为这两个变量引用相同的列表。

Fo r示例如下demoList<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); 
     } 

} 

补充阅读

相关问题