在這種情況下,反射是你最好的朋友。
下面是一個財產複印機的粗略實施。您只需要新建一個目標類型的實例,並將其傳遞給具有所有屬性值設置的源實例。
編輯:正如馬克已經指出的,這隻會在瑣碎的屬性映射方面做伎倆。帶上一粒鹽吧。
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