copy a class, C#
Is there a way to copy a class in C#? Something like var dupe = MyClass(original).
You are probably talking about a deep copy (deep copy vs shallow copy)?
You either have to:
[Serializable]
attribute. public static T DeepCopy<T>(T other)
{
using (MemoryStream ms = new MemoryStream())
{
BinaryFormatter formatter = new BinaryFormatter();
formatter.Serialize(ms, other);
ms.Position = 0;
return (T)formatter.Deserialize(ms);
}
}
To get a shallow copy, you can use the Object.MemberwiseClone()
method, but it is a protected method, which means you can only use it from inside the class.
With all the deep copy methods, it is important to consider any references to other objects, or circular references which may result in creating a deeper copy than what you wanted.
Not all classes have this functionality. Probably, if a class does, it provides a Clone
method. To help implement that method for your own classes there's a MemberwiseClone
protected method defined in System.Object
that makes a shallow copy of the current instance (ie fields are copied; if they are reference types, the reference will point to the original location).
If your class has just got properties, you could do something like this:
SubCentreMessage actual;
actual = target.FindSubCentreFullDetails(120); //for Albany
SubCentreMessage s = new SubCentreMessage();
//initialising s with the same values as
foreach (var property in actual.GetType().GetProperties())
{
PropertyInfo propertyS = s.GetType().GetProperty(property.Name);
var value = property.GetValue(actual, null);
propertyS.SetValue(s, property.GetValue(actual, null), null);
}
If you have fields and methods, I am sure you can recreate them in new class using reflections. Hope this helps
链接地址: http://www.djcxy.com/p/79362.html上一篇: 在c ++中的默认赋值operator =是一个浅拷贝?
下一篇: 复制一个类,C#