从另一个对象创建对象
问题描述:
原谅愚蠢的newby问题,但... 我正在将数据从一个表移动到另一个表。目标表模式与源表完全相同,只是它有几个额外的列。 Linq to SQL生成类来表示每个表。如果我有一个源对象,我该如何从它创建一个目标对象?例如,源对象具有属性A,B,C。目标对象具有A,B,C,X,Y。我想要做的事,如:从另一个对象创建对象
Destination dest = new Destination(Source source, int x, int y)
{
this.X = x;
this.Y = y;
...
// somehow set all the destination properties to
// their corresponding source value
}
有一种优雅的方式比显式设置每个属性做到这一点其他的? 我可以让Destination从源代码继承吗?这会有帮助吗?
答
如果类型无关,MiscUtil有:
Destination dest = PropertyCopy<Destination>.CopyFrom(source);
然后手动设置:
dest.X = x;
dest.Y = y;
你可以写或者一个转换方法/操作员,但你需要保持它( PropertyCopy
是自动的)。
重申你的继承点;我认为这不太合适。你可能做部分类的东西,但它不会与LINQ到SQL一起工作,如果你这样做(它处理继承本身,并不会喜欢你这样做)。
答
您可以在您传递源代码的对象中使用复制构造函数,并手动将它的字段复制到目标。但是,这需要大量的手动编码。
您也可以使用像AutoMapper这样的库为您自动执行此操作。您可以定义该源可映射到目标(无非是),并根据项目名称为您解决问题。另外,如果你纯粹只是移动数据(我假设在一个数据库中),你可以使用纯SQL来做到这一点,而不需要任何代码吗?
答
为什么不能用Reflection创建自己的自动转换?你可以做一些事情来的
class Program {
static void Main(string[] args)
{
Source item1 = new Source(2, 3, 4);
Destination item2 = new Destination(item1, ContinueCopy);
Console.WriteLine(string.Format("X: {0}\n Y: {1}", item2.X, item2.Y));
Console.ReadKey();
}
public static bool ContinueCopy(string name, Type type)
{
if (name == "X" && type == typeof(int)) return false;
return true;
}
}
public class Source {
public Source() { }
public Source(int x, int y, int z)
{
myX = x;
myY = y;
myZ = z;
}
private int myX;
public int X
{
get { return myX; }
set { myX = value; }
}
private int myY;
public int Y
{
get { return myY; }
set { myY = value; }
}
private int myZ;
public int Z
{
get { return myZ; }
set { myZ = value; }
}
}
public class Destination {
public delegate bool ContinueCopyCallback(string propertyName, Type propertyType);
public Destination() : this(0,0) { }
public Destination(int x, int y)
{
myX = x;
myY = y;
}
public Destination(Source copy) : this(copy, null) { }
public Destination(Source copy, ContinueCopyCallback callback)
{
foreach (PropertyInfo pi in copy.GetType().GetProperties())
{
PropertyInfo pi2 = this.GetType().GetProperty(pi.Name);
if ((callback == null || (callback != null && callback(pi.Name,
pi.PropertyType))) && pi2 != null && pi2.GetType() == pi.GetType())
{
pi2.SetValue(this, pi.GetValue(copy, null), null);
}
}
}
private int myX;
public int X
{
get { return myX; }
set { myX = value; }
}
private int myY;
public int Y
{
get { return myY; }
set { myY = value; }
}
}
调输出将给item2.X值2和item2.Y的3
值时,也可以提供有一个回调的能力,这可以让您对不希望自动复制的属性名称进行自定义过滤。您也可以将复制代码编写为接受Source作为参数的Destination的浅拷贝构造函数。
这是一种轻量级的方法,因为您的需求非常简单。