假设我有一个类型为User的对象,看起来像这样:
User {
Name = "Bob",
Email = "[email protected]",
Class = NULL
}
谁能想到一种获取该对象并创建这样的对象的方法:
User {
Name = "Bob",
Email = "[email protected]"
}
使用完全通用的代码?意思是,我不想硬编码与“类型”或“属性”有关的任何内容,因为此代码需要应用于我网站上的每个实体。 (顺便说一句,“用户”类型是实体,因此,如果可以帮助您更好地编写代码,请使用它)。
我只是想提出一个解决我遇到的问题的方法,我相信Stub Entities可以解决问题,但是我需要在不对任何类型或属性进行硬编码的情况下进行操作。
最佳答案
使用反射实现此目的:
public void CopyValues<TSource, TTarget>(TSource source, TTarget target)
{
var sourceProperties = typeof(TSource).GetProperties().Where(p => p.CanRead);
foreach (var property in sourceProperties)
{
var targetProperty = typeof(TTarget).GetProperty(property.Name);
if (targetProperty != null && targetProperty.CanWrite && targetProperty.PropertyType.IsAssignableFrom(property.PropertyType))
{
var value = property.GetValue(source, null);
targetProperty.SetValue(target, value, null);
}
}
}