通用集合复制方法

时间:2016-09-02 08:17:14

标签: c# reflection

我有这个有用的小方法,它使用反射来复制单个类实例。它的优点是可以在不完全相同的类之间进行复制,只需复制匹配的属性即可。我经常使用它。

public static void ObjectCopy(object source, object target)
{
    if (source != null && target != null)
    {
        foreach (var prop in target.GetType().GetProperties())
        {
            var FromProp = source.GetType().GetProperty(prop.Name);
            if (FromProp != null)
            {
                prop.SetValue(target, FromProp.GetValue(source));
            }
        }
    }
}

我现在要求做类似的事情,但有一个集合,即ObservableCollection或List。我正在努力弄清楚如何在通用例程中做到这一点。我可以在新的例程中调用旧例程来进行集合项复制,但处理集合本身就是我所挣扎的。

有什么想法吗?

我需要能够复制不同(但类似)类的集合。我的例子是ObservableCollection的ObservableCollection。它们具有共同的属性,但也存在一些差异。

很抱歉没有更具体。

2 个答案:

答案 0 :(得分:1)

这可能会这样做。仅适用于馆藏。

public static void ObjectCollection<TC, TK>(ICollection source, TC target)
    where TC : class, ICollection<TK>, new()
    where TK : class, new()
{
    foreach (var item in source)
    {
        var copiedItem = new TK();
        ObjectCopy(item, copiedItem);
        target.Add(copiedItem);
    }
}

使用示例:

public class Data { public string Test { get; set; } }
public class Data2 { public string Test { get; set; } }

var source = new Data[3] {
    new Data { Test = "1" },
    new Data { Test = "2" },
    new Data { Test = "3" }
};
var target = new List<Data2>();
ObjectCollection<List<Data2>, Data2>(source, target);

答案 1 :(得分:1)

您可以尝试使用以下内容将两个不同类型的现有集合连接在一起:

public static void MapCollections<T1, T2, TKey>(IEnumerable<T1> target, IEnumerable<T2> values,
        Func<T1, TKey> targetKeySelector, Func<T2, TKey> valueKeySelector)
{
    foreach (var pair in target.Join(values, targetKeySelector, valueKeySelector, (t, v) => new { target = t, value = v}))
    {
        ObjectCopy(pair.value, pair.target);
    }
}

您可能需要使用其他一些约束来管理重复键等。