在这种情况下,反射是你最好的朋友。
下面是一个财产复印机的粗略实施。您只需要新建一个目标类型的实例,并将其传递给具有所有属性值设置的源实例。
编辑:正如马克已经指出的,这只会在琐碎的属性映射方面做伎俩。带上一粒盐吧。
using System;
using System.Collections.Generic;
using System.Text;
using System.Reflection;
namespace StackOverflow
{
public static class ReflectionHelper
{
public static void CopyPropertyValues(object source, object target)
{
if (source == null) throw new ArgumentNullException("source");
if (target == null) throw new ArgumentNullException("target");
var sourceType = source.GetType();
var targetType = target.GetType();
var sourceProperties = sourceType.GetProperties();
foreach (var sourceProperty in sourceProperties)
{
if (sourceProperty.CanRead)
{
var targetProperties = targetType.GetProperties();
foreach (var targetProperty in targetProperties)
{
if (targetProperty.Name == sourceProperty.Name &&
targetProperty.PropertyType == sourceProperty.PropertyType)
{
if (targetProperty.CanWrite)
{
var value = sourceProperty.GetValue(source, null);
targetProperty.SetValue(target, value, null);
}
break;
}
}
}
}
}
}
}
您可以移动到至少NET 3.0?使用WCF,你可以共享一个DataContract对象的公共DLL,允许你严格重用同一个对象。 –
不能使用任何东西,但.NET2.0。可能需要使用Mono和.NET Compact(对于CE5.0),所以我试图让解决方案尽可能简单。 – Sparers