我是一个彻头彻尾的菜鸟,所以如果我不适合问这个问题,请告诉我,如果需要,请给我引导。
无论如何......我一直在学习值类型和引用类型,并且想知道定义一个额外的构造函数(然后稍后调用它)是否是创建类副本的有效方法。我尝试用一个简单的类对其进行测试,它似乎有效。
public ClassClass(ClassClass exampleClass)
{
var1 = exampleClass.var1;
var2 = exampleClass.var2;
// ...
}
...
复制对象有两种。
- 引用副本
- 值(value)复制
要通过引用复制对象,您只需使用“=”运算符即可。
例如:
var o1 = new ClassClass();
var o2 = o1;
按值复制一个对象,有几种方法,例如:
Copy by a constructor (as you wrote)
public class Student
{
public string FirstName { get; set; }
public string LastName { get; set; }
public Student(Student std)
{
FirstName = std.FirstName;
LastName = std.LastName;
}
}
Make a helper class an pass the s1 as input and return s2 as
result
static void Main(string[] args)
{
var s1 = new Student();
var s2 = ClassHelper.CopyObject(s1);
}
public static class ClassHelper
{
public static Student CopyObject(Student std)
{
var newStudent = new Student()
{
FirstName = std.FirstName,
LastName = std.LastName
};
return newStudent;
}
}
Generic Copy Objects (using Refelection)
private static void CopyClass<T>(T copyFrom, T copyTo, bool copyChildren)
{
if (copyFrom == null || copyTo == null)
throw new Exception("Must not specify null parameters");
var properties = copyFrom.GetType().GetProperties();
foreach (var p in properties.Where(prop => prop.CanRead && prop.CanWrite))
{
if (p.PropertyType.IsClass && p.PropertyType != typeof(string))
{
if (!copyChildren) continue;
var destinationClass = Activator.CreateInstance(p.PropertyType);
object copyValue = p.GetValue(copyFrom);
CopyClass(copyValue, destinationClass, copyChildren);
p.SetValue(copyTo, destinationClass);
}
else
{
object copyValue = p.GetValue(copyFrom);
p.SetValue(copyTo, copyValue);
}
}
}
Write an extension method for this class and I recommended to do this.
public static class ExtensionClass
{
public static Student CopyAsNewObject(this Student std)
{
var newStudent = new Student()
{
FirstName = std.FirstName,
LastName = std.LastName
};
return newStudent;
}
}
static void Main(string[] args)
{
var s1 = new Student();
var s2 = s1.CopyAsNewObject();
}