Tag: 浅拷贝

如何创建列表集的深层副本

假设我有以下课程: public class Author { public int ID {get; private set;} public string firstName {get; private set;} public string lastName {get; private set; } public Author(int id, string firstname, string lastname) { this.ID = ID; this.firstName = firstname; this.lastName = lastName; } public static Author Clone(Author clone) { Author copyAuth = new Author(clone.ID, clone.firstName, clone.lastName); […]

为什么List的副本仍使用C#更改原始List中的属性

可以说我有这门课 public class Employee { public string FirstName { get; set; } public string LastName { get; set; } public bool isActive { get; set; } } 并像这样使用它: List Employees = new List(); Employees.Add(new Employee { FirstName = “firstname”, LastName = “lastname”, isActive = true }); List EmployeesCopy = new List(Employees); EmployeesCopy[0].isActive = false; 为什么更改EmployeesCopy […]

为什么对象会通过引用自动传递?

在C#的pass-by-reference-pass-by-value-concept的上下文中,我有一个关于深度和浅拷贝的一般性问题: 在C#中,需要显式创建接受指针/引用的方法,以便能够将此类方法传递给该方法。 但是,至少作为参数传递给方法/构造函数的对象的行为与其他对象不同。 如果没有按照此处所述进行额外的克隆,它们似乎总是通过引用传递:http: //zetcode.com/lang/csharp/oopii/ 。 为什么对象会通过引用自动传递? 在这些情况下,强制克隆过程是否有任何特别的好处,而不是更像int,double,boolean等处理对象? 这是代码示例,说明我的意思: using System; public class Entry { public class MyColor { public int r = 0; public int g = 0; public int b = 0; public double a = 1; public MyColor (int r, int g, int b, double a) { this.r = r; this.g = […]

你会如何改进这种浅层复制课程?

我用一个静态方法编写了一个类,它将属性值从一个对象复制到另一个对象。 它不关心每个对象是什么类型,只关心它们具有相同的属性。 它做了我需要的,所以我不会进一步设计它,但你会做出哪些改进? 这是代码: public class ShallowCopy { public static void Copy(From from, To to) where To : class where From : class { Type toType = to.GetType(); foreach (var propertyInfo in from.GetType().GetProperties(BindingFlags.GetProperty | BindingFlags.Public | BindingFlags.Instance)) { toType.GetProperty(propertyInfo.Name).SetValue(to, propertyInfo.GetValue(from, null), null); } } } 我正在使用它如下: EmployeeDTO dto = GetEmployeeDTO(); Employee employee = new Employee(); […]