我
class A
{
public int a;
public string b;
}
我怎么能复制到另一部分?在C ++中,我知道我能做到 * A1 = A2 *;
。有没有在C#中类似的东西?我知道我可以使用反射编写一个通用的解决方案,但我希望的东西已经存在了。
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.
步骤2,我需要做的。
class B : A {}
class C : A {}
和从B基础数据复制到C。
and copy the base data from B to C.
下面是一些简单的code对任何一类的作品,不只是基地。
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)
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);
}
}