是否有一种简单的方法可以基本上只使用此方法获取数据的副本而不是引用?我试过.ToArray().Where()但似乎仍然传递了一个引用.
例:
static void Main(string[] args)
{
List<ob> t = new List<ob>();
t.Add(new ob() { name = "hello" });
t.Add(new ob() { name = "test" });
ob item = t.Where(c => c.name == "hello").First();
// Changing the name of the item changes the original item in the list<>
item.name = "burp";
foreach (ob i in t)
{
Console.WriteLine(i.name);
}
Console.ReadLine();
}
public class ob
{
public string name;
}
Run Code Online (Sandbox Code Playgroud)
你需要自己创建一个副本ob
- 这不是LINQ提供的.
Clone
您可以基于现有方法定义一个方法protected MemberwiseClone
:
public class Item
{
public Item Clone()
{
return (Item)this.MemberwiseClone();
}
}
Run Code Online (Sandbox Code Playgroud)
然后:
ob item = t.Where(c => c.name == "hello").First().Clone();
Run Code Online (Sandbox Code Playgroud)