开发者

Copy a class to another?

I have

class A
{
    public int a;
    public string b;
}

How can i copy A to another A? In C++ i know i could do *a1 = *a2;. Is there something similar in C#? I know i could write a generic solution using reflection but i hope something exist already.

I'm considering changing A to a nullable struct.

Step 2 i'll need to do

class B : A {}
class C : 开发者_JS百科A {}

and copy the base data from B to C.


I have used binary serialization. Basically, serialize the instance to a memory stream. Then, deserialize it out of the memory stream. You will have an exact binary copy. It will be a deep copy, rather than a shallow copy.

class a = new ClassA();

class b = MySerializationMethod(a);

For a shallow copy you can use Object.MemberwiseClone


Here is some simple code that works on any class, not just base.

    public static void DuckCopyShallow(this Object dst, object src)
    {
        var srcT = src.GetType();
        var dstT= dst.GetType();
        foreach(var f in srcT.GetFields())
        {
            var dstF = dstT.GetField(f.Name);
            if (dstF == null || dstF.IsLiteral)
                continue;
            dstF.SetValue(dst, f.GetValue(src));
        }

        foreach (var f in srcT.GetProperties())
        {
            var dstF = dstT.GetProperty(f.Name);
            if (dstF == null)
                continue;
            
            dstF.SetValue(dst, f.GetValue(src, null), null);
        }
    }


Assuming A is just a simple class, you can do

A newA = instanceOfA.MemberwiseClone();

MemberwiseClone() is a shallow copy though, so if your class gets complex, with properties that are also reference types, this will not work for you.


there is the ICloneable interface which offers up a Clone() method.

Clone on msdn.


Here's what somebody has already done...

Deep Copy in C# (Cloning for a user defined class)


Add the appropriate constructors:

class Foo
{
    public Foo(int a, string b)
    {
        A = a;
        B = b;
    }

    public Foo(Foo other)
    {
        A = other.A;
        B = other.B;
    }

    public int A { get; set; }
    public string B { get; set; }
}

You should also consider making it immutable, especially if you are considering making it into a struct. Mutable structs are evil.

Finally when you are inheriting from a class you don't need to copy the members from the base class into the subclass.


We've used this code successfully:

using System;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;

namespace Utility {
    internal static class ObjectCloner {
        public static T Clone<T>(T obj) {
            using (MemoryStream buffer = new MemoryStream()) {
                BinaryFormatter formatter = new BinaryFormatter();
                formatter.Serialize(buffer, obj);
                buffer.Position = 0;
                T temp = (T)formatter.Deserialize(buffer);
                return temp;
            }
        }
    }
}

There may be other methods which work better, but perhaps this will help you

Chris


You can Clone, you can define a copy constructor. Why change class to struct just because in C++ you can do something in 10 characters. C# is different. Structs have advantages and disadvantages.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜