将对象数据复制到堆位置

时间:2017-12-05 20:22:32

标签: c# list reference heap

我有以下代码:

public class Entity
{
    public int Number;
    public string Text;
}

System.Collections.Generic.List<Entity> list = new List<Entity>();
list.Add(new Entity() { Number = 100, Text = "hello1" });
list.Add(new Entity() { Number = 200, Text = "hello2" });

Entity sampleEntity = new Entity() { Number = 300, Text = "World" };

list[0] = sampleEntity // this does only replace the pointer in the list

list[0].Text = sampleEntity.Text; // this writes to the pointer in list
list[0].Number = sampleEntity.Number; // this writes to the pointer in list

如果有任何可能的方法将整个对象数据的memcopy执行到list[0]条目指向的堆位置,我想知道什么?我的意思是在c ++中它是一个简单的解引用*list[0] = *entity;

1 个答案:

答案 0 :(得分:0)

除非Entity实施ICloneable(见Creating a copy of an object in C#)。

我个人只是实例化一个新的Entity

list[0] = new Entity { Number = sampleEntity.Number, Text = sampleEntity.Text };