3

同じ名前とフィールドのタイプを持つ 2 つのクラスがあるとします。

class A
 {
  private int x;
  private string y;
 }

class B
 {
  private int x;
  private string y;
 }

A a = new A();
B b = new B();
a.x = 5;
a.y = "xxx";

a を b に「コピー」または「割り当てる」ことは可能ですか? 「b=a」のように簡単な方法はありますか?

4

5 に答える 5

0

C# でこれを行う簡単な方法はありません。ただし、式ツリーを
使用して独自のメソッドを動的に生成し、このコピーを行うことができます。ILGenerator(やったことがないと難しいかもしれませんが。)

例:

using System;
using System.Reflection;
using System.Reflection.Emit;

public class Foo
{
    private int a;
    public Foo(int a) { this.a = a; }
}

public class Program
{
    private int a;
    private static void Main()
    {
        var prog1 = new Foo(1);
        var prog2 = new Program() { a = 2 };
        TypeHelper<Foo, Program>.Copy(prog1, prog2);
    }
}

public static class TypeHelper<T1, T2> where T1 : class where T2: class
{
    public delegate void CopyAction(T1 from, T2 to);
    public static readonly CopyAction Copy = new Converter<Type, CopyAction>(t1 =>
    {
        var method = new DynamicMethod(string.Empty, null, new Type[] { t1, typeof(T2) }, t1, true);
        var gen = method.GetILGenerator();
        foreach (var field in t1.GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic))
        {
            gen.Emit(OpCodes.Ldarg_1);
            gen.Emit(OpCodes.Ldarg_0);
            gen.Emit(OpCodes.Ldfld, field);
            gen.Emit(OpCodes.Stfld, typeof(T2).GetField(field.Name, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic));
        }
        return (CopyAction)method.CreateDelegate(typeof(CopyAction));
    })(typeof(T1));
}
于 2013-08-31T17:23:50.890 に答える
-1

Marshal.StructureToPtrと でそれができると思いますMarshal.PtrToStructure

Marshal.StructureToPtr メソッド (MSDN)の例を参照してください。

于 2013-08-31T17:20:33.197 に答える