0

我使用以下代码使用源对象创建特定目标类型的新实例,其中我将所有原始类型属性值从源对象复制到目标对象:

Function GetDestinationObjectFromSourceObject(pSourceObject As Object, pDestinationType As Type) As Object
            Dim oDestinationObject = Activator.CreateInstance(pDestinationType)

            For Each oPropertyDescriptor As PropertyDescriptor In TypeDescriptor.GetProperties(pSourceObject)
                If TypeDescriptor.GetProperties(oDestinationObject).Contains(oPropertyDescriptor) Then
                    TypeDescriptor.GetProperties(oDestinationObject).Item(oPropertyDescriptor.Name).SetValue(oDestinationObject, oPropertyDescriptor.GetValue(pSourceObject))
                End If
            Next

            Return oDestinationObject
End Function

现在。我有一个 List(Of Class1) 并希望使用相同的通用方法获取 List(Of Class2)。在这里,我想通过 List(Of Class1) 和目标类型(即 GetType(Class2)) 我怎样才能实现相同的目标?

4

1 回答 1

0

如果我正确理解了您的问题,那么您可以遍历 List(of Class1) 并将每个对象传递给此方法,并将返回的对象添加到新的 List(of Class2) 中。

例如(我在 c# 中放了一个代码,因为我在 vb.net 中有点弱,但是将它转换为 vb.net 对你来说应该不是问题)

如果这不是您所需要的,请重新表述您的问题。

List<Class2> newlstClass2 = new List<Class2>();
foreach(Class1 item in lstClass1)
{
    newlstClass2.Add(GetDestinationObjectFromSourceObject(item, typeof(Class2)));
}

编辑:

以下是满足您要求的通用方法。我假设这些类有一个无参数的构造函数。我已经从我的最后测试了一点。请在您的最后进行彻底的测试。

public List<U> GenerateList<T, U>(List<T> lst)
{
    List<U> newLst = new List<U>();

    foreach (var item in lst)
    {
        U obj = Activator.CreateInstance<U>();
        foreach (PropertyInfo item2 in item.GetType().GetProperties())
        {
            if (obj.GetType().GetProperty(item2.Name) != null)
            {
                obj.GetType().GetProperty(item2.Name).SetValue(obj, item2.GetValue(item, null), null);
            }
        }

        newLst.Add(obj);
    }

    return newLst;
}

希望这可以帮助。

于 2014-02-21T06:19:27.363 回答