列表不要复制到结构中

时间:2015-07-08 15:32:37

标签: c# list struct

所以我有这个结构

public struct Way
    {
        public Int64 ID;
        public List<Int64> Ref; //contains a list with Node IDs
        public List<string> Tag;
        public List<string> Value;

        public Way(Int64 id, List<Int64> refe, List<string> tage, List<string> valuee)
        {
        ID = id;
        Ref = new List<Int64>(refe); //contains a list with Node IDs
        Tag = new List<string>(tage);
        Value = new List<string>(valuee); // This list is ALWAYS the same lenght as the Tag list
        }

    };

此结构用作基本模板,用于存储从大文件中检索的数据。所以我创建了一个这个结构的列表来存储所有数据。

public List<Way> WayList = new List<Way>();

在处理算法中,我使用临时结构临时存储每个数据,同时逐行处理文件(1路数据可以跨越4行到800-1000行文本或更多)。

List<Int64> a = new List<Int64>();
List<string> b = new List<string>();
List<string> c = new List<string>();
Way FoundWay = new Way(0, a, b, c);

然后我使用Add函数将此临时结构添加到列表中。

 WayList.Add(CopyWay);

在调试模式下,这就是发生的事情。临时结构中包含正确的数据。但是当我将这个结构添加到WayList中时,会发生这种情况:

    - the ID gets input by value (each way in the list has an unique ID = good)
    - the lists gets input by reference ( each way in the list has the same lists = bad)

我的问题是,有没有办法按值获取这些列表输入,还是我需要放弃使用结构?

1 个答案:

答案 0 :(得分:0)

This probably shouldn't be a struct. It seems to more "naturally" be a class, though there might be a reason for using a struct that isn't obvious here (though a mutable struct is a dangerous thing, best only used very carefully and with the struct itself private or internal so that the great many complications with mutable structs don't cause problems).

Either way though:

the lists gets input by reference

Not quite. The lists get input by value, but that value is in itself a reference, because List<T> is a reference type. If you want to create a copy of a list you must do exactly that; copy the list. This holds whether the containing object is a reference or value type.

A simple way to do that would be to add a copy-constructor:

public Way (Way way)
  : this(way.ID, new List<Int64>(way.Ref), new List<string>(way.Tag), new List<string>(way.Value))
{
}

And then use it:

WayList.Add(new Way(CopyWay));