C# 复制列表值

C# 复制列表值,c#,C#,当我调用此方法时,总是更改原始列表printRowList中的值,我不想更改原始值。我只需要更改temp List的值,即tempRowModellist。我能做什么 private List<PrintRowModel> SetTemplateSettingsData( List<PrintRowModel> printRowList, object value) { List<PrintRowModel> tempRowModel

当我调用此方法时,总是更改原始列表printRowList中的值,我不想更改原始值。我只需要更改temp List的值,即tempRowModellist。我能做什么

private List<PrintRowModel> SetTemplateSettingsData(
    List<PrintRowModel> printRowList, 
    object value)
{
    List<PrintRowModel> tempRowModellist = new List<PrintRowModel>();
    tempRowModellist.AddRange(printRowList);

    foreach (PrintRowModel printRow in tempRowModellist )
    {
        foreach (PrintColumnModel printColumn in printRow)
        {
            printColumn.Value = 
                GetObjectValues(printColumn.Value, value).ToString();
        }
    }

    return newList;
}

因为您仍在引用原始列表。如果不想修改它,则需要克隆它。 改变这个

tempRowModellist.AddRange(printRowList);`
作为

加上这个


注意:确保您的类实现了I.

,因为您仍然在引用原始列表。如果不想修改它,则需要克隆它。 改变这个

tempRowModellist.AddRange(printRowList);`
作为

加上这个


注意:确保类实现了I。

两个列表都存储了指向相同实际PrintRowModel对象的引用指针。如果要创建完全独立的列表,则需要复制列表和存储在列表中的对象

两个列表都存储指向相同实际PrintRowModel对象的引用指针。如果要创建完全独立的列表,则需要复制列表和存储在列表中的对象

之所以会发生这种情况,是因为“添加范围”通过引用复制它,所以您可以更改原始对象

之所以会发生这种情况,是因为“添加范围”通过引用复制它,所以您可以更改原始对象

在此查找克隆方法,此方法将反序列化原始对象并返回原始对象的副本,这是必需的,因为更改引用对象将影响原始对象。

在此查找克隆方法,此方法将反序列化原始对象并返回原始对象的副本,这是必需的,因为更改引用对象将影响原始对象。

如果您了解了不同的b/w值类型和引用类型,您将得到您的答案如果您了解了不同的b/w值类型和引用类型,您将得到您的答案i=>i.Clone.ToList;我添加了扩展方法,但它说类型bla blaa不能用作泛型类型或方法blaa blaa中的类型参数“T”…没有隐式引用转换,您可以发布确切的异常吗?错误11类型“YMax.POS.Printer.PrintColumnModel”不能用作泛型类型或方法中的类型参数“T”'YMax.POS.Printer.Extensions.CloneSystem.Collections.Generic.IList'。没有从“YMax.POS.Printer.PrintColumnModel”到“System.iclonable.G:\Tharindu\Hg\YMax.POS.Printer\YMax.POS.Printer\YMax.POS.Printer\SerialPrinter.cs 485 62 YMax.POS.Printer”的隐式引用转换以及您如何使用它的调用?List tempRowModellist=new ListprintRowList;tempRowModellist=printRowList.Selecti=>i.Clone.ToList;我在I=>I.Clone.ToList中出错;我添加了扩展方法,但它说类型bla blaa不能用作泛型类型或方法blaa blaa中的类型参数“T”…没有隐式引用转换,您可以发布确切的异常吗?错误11类型“YMax.POS.Printer.PrintColumnModel”不能用作泛型类型或方法中的类型参数“T”'YMax.POS.Printer.Extensions.CloneSystem.Collections.Generic.IList'。没有从“YMax.POS.Printer.PrintColumnModel”到“System.iclonable.G:\Tharindu\Hg\YMax.POS.Printer\YMax.POS.Printer\YMax.POS.Printer\SerialPrinter.cs 485 62 YMax.POS.Printer”的隐式引用转换以及您如何使用它的调用?List tempRowModellist=new ListprintRowList;tempRowModellist=printRowList.Selecti=>i.Clone.ToList;
static class Extensions
{
    public static List<T> Clone<T>(this List<T> listToClone) where T: ICloneable
    {
        return listToClone.Select(item => (T)item.Clone()).ToList();
    }
}