C# 将值从字典复制到字典而不是地址
我试图将值从一个字典复制到另一个字典,因此,当新字典中的值发生更改时,它不会更改旧值。现在我想我是在抄地址C# 将值从字典复制到字典而不是地址,c#,dictionary,value-type,reference-type,C#,Dictionary,Value Type,Reference Type,我试图将值从一个字典复制到另一个字典,因此,当新字典中的值发生更改时,它不会更改旧值。现在我想我是在抄地址 public Cube Right(Cube cube) { Dictionary<SidePosition, Side> newSides = new Dictionary<SidePosition, Side>(cube.Sides); for (int i = 0; i < RightSideOrder.Count;
public Cube Right(Cube cube) {
Dictionary<SidePosition, Side> newSides = new Dictionary<SidePosition, Side>(cube.Sides);
for (int i = 0; i < RightSideOrder.Count; i++) {
for (int j = 0; j < RightFaceOrder.Count; j++) {
newSides[RightSideOrder[i]].Faces[RightFaceOrder[j]] =
cube.Sides[RightSideOrder[GetAntecedantSideIndex(i)]]
.Faces[RightFaceOrder[j]];
}
}
return cube;
}
private int GetAntecedantSideIndex(int currentIndex) {
if (currentIndex == 0)
return 3;
return currentIndex - 1;
}
}
公共多维数据集权限(多维数据集){
Dictionary newSides=新字典(cube.Sides);
for(int i=0;i
Cube
和它的Side
字典中包含的值都是结构。我对C#很陌生,所以如果命名约定被取消,我深表歉意
根据我的研究/与人交谈,解决方案可能涉及iClonable或新的IDictionary实现,但迄今为止,这两种实现中的任何一种都没有成功
如果需要更多详细信息,可在此处找到完整项目:
代码摘录自一个名为CubeManipulator的类
TLDR;如何从字典中获取值作为值类型
您可以使用深度复制操作
执行深度复制操作时,克隆的Person对象,
包括其Person.IdInfo属性,可以在不使用
影响原始对象的
比如:
public class SidePosition
{
public IdInfo IdInfo;
public SidePosition DeepCopy()
{
SidePosition other = (SidePosition) this.MemberwiseClone();
other.IdInfo= new IdInfo(IdInfo.IdNumber);
return other;
}
}
public class Side
{
public IdInfo IdInfo;
public Side DeepCopy()
{
Side other = (Side) this.MemberwiseClone();
other.IdInfo= new IdInfo(IdInfo.IdNumber);
return other;
}
}
public Cube Right(Cube cube) {
Dictionary<SidePosition, Side> newSides = new Dictionary<SidePosition, Side>();
foreach(var item in cube.Sides)
newSides.Add(new SidePosition(item.key), new Side(item.value));
//your logic
}
公共类侧置
{
公共信息;
公开侧置DeepCopy()
{
SidePosition other=(SidePosition)this.MemberwiseClone();
other.IdInfo=新的IdInfo(IdInfo.IdNumber);
归还他人;
}
}
公营部门
{
公共信息;
公开副本()
{
Side other=(Side)this.MemberwiseClone();
other.IdInfo=新的IdInfo(IdInfo.IdNumber);
归还他人;
}
}
公共多维数据集权限(多维数据集){
Dictionary newSides=新字典();
foreach(多维数据集中的变量项)
添加(新边位置(item.key),新边(item.value));
//你的逻辑
}
查看下面的链接,查看制作词典副本的示例,以便在副本后更改一个词典中的值不会影响另一个词典:
如果你能提供一个我可以复制并粘贴到控制台应用程序中重新制作问题的工具,那就太棒了。有两个想法值得记住:1。深度复制(下面的答案)2。不可变对象(如果可能,许多算法更简单、更安全)