sourceObject到DestinationObject的映射列表
本文关键字:映射 列表 DestinationObject sourceObject | 更新日期: 2023-09-27 18:01:41
我正在使用的代码应用属性值从一个对象到另一个相同类型的自动?
public static class Reflection
{
/// <summary>
/// Extension for 'Object' that copies the properties to a destination object.
/// </summary>
/// <param name="source">The source.</param>
/// <param name="destination">The destination.</param>
public static void CopyProperties(this object source, object destination)
{
// If any this null throw an exception
if (source == null || destination == null)
throw new Exception("Source or/and Destination Objects are null");
// Getting the Types of the objects
Type typeDest = destination.GetType();
Type typeSrc = source.GetType();
// Iterate the Properties of the source instance and
// populate them from their desination counterparts
PropertyInfo[] srcProps = typeSrc.GetProperties();
foreach (PropertyInfo srcProp in srcProps)
{
if (!srcProp.CanRead)
{
continue;
}
PropertyInfo targetProperty = typeDest.GetProperty(srcProp.Name);
if (targetProperty == null)
{
continue;
}
if (!targetProperty.CanWrite)
{
continue;
}
if (targetProperty.GetSetMethod(true) != null && targetProperty.GetSetMethod(true).IsPrivate)
{
continue;
}
if ((targetProperty.GetSetMethod().Attributes & MethodAttributes.Static) != 0)
{
continue;
}
if (!targetProperty.PropertyType.IsAssignableFrom(srcProp.PropertyType))
{
continue;
}
// Passed all tests, lets set the value
targetProperty.SetValue(destination, srcProp.GetValue(source, null), null);
}
}
}
这一切都很好!
我遇到的麻烦是如何创建一个类似的函数,该函数将源列表复制到目标列表,并使用它来调用上面的代码。
当然这行不通,但是像
这样 public static void CopyListProperties(this List<object> sourceList, List<object> destinationList)
{
foreach (var item in sourceList)
{
var destinationObject = new destinationObjectType();
item.CopyProperties(destinationObject);
destinationList.Add(destinationObject);
}
}
感谢Alex。
函数应该是这样的。
public static void CopyListProperties<T>(this List<object> sourceList, List<T> destinationList) where T: new()
{
foreach (var item in sourceList)
{
var destinationObject = new T();
item.CopyProperties(destinationObject);
destinationList.Add(destinationObject);
}
}