0

我有这个类的两个对象:

public class A
{
    public int Id { get; set; }
    public string Name { get; set; }
    public IList<B> Bs { get; set; }
}

public class B
{
    public string Description { get; set; }
    public IList<C> Cs { get; set; }
}

public class C
{
    public string Description { get; set; }
}

现在我想用 FastMember 遍历两个对象实例的所有属性,并将属性从 复制object 1object 2.

这是我到目前为止得到的(不工作!)

// Set accessors
var sourceAccessor = ObjectAccessor.Create(object1);
var targetAccessor = ObjectAccessor.Create(object2);

foreach (var sourceItem in (IList)sourceAccessor.Target)
{
    var targetItemAccessor = ObjectAccessor.Create(targetAccessor.Target);
    var sourceItemAccessor = ObjectAccessor.Create(sourceItem);

    // Overwrite property
    targetItemAccessor[p] = sourceItemAccessor[p];
}

这段代码显然不起作用......有什么想法吗?谢谢!

4

1 回答 1

0

您可以在使用以下内容的帮助下创建浅拷贝TypeAccessor

var sourceAccessor = ObjectAccessor.Create(object1);
var targetAccessor = ObjectAccessor.Create(object2);

var access = TypeAccessor.Create(typeof(A));
var members = access.GetMembers();

foreach (var member in members)
{
    targetAccessor[member.Name] = sourceAccessor[member.Name];
}

查看FastMember 测试以获取使用示例。

对于深拷贝,您可以检查属性名称或使用属性类型来确定是应用列表的深拷贝还是浅拷贝就足够了。

编辑:这是递归复制类型属性的简化版本的示例IList(请参阅this question on how to determine which property is a list),假设源和目标对象的列表具有相同的长度:

private static void MirrorObject(object object1, object object2)
{
    var sourceAccessor = ObjectAccessor.Create(object1);
    var targetAccessor = ObjectAccessor.Create(object2);

    var access = TypeAccessor.Create(object1.GetType());
    var members = access.GetMembers();

    foreach (var member in members)
    {
        if (member.Type.IsGenericType && (member.Type.GetGenericTypeDefinition() == typeof(IList<>)))
        {
            var list1 = (IList)sourceAccessor[member.Name];
            var list2 = (IList)targetAccessor[member.Name];
            if (list1.Count != list2.Count)
            {
                throw new ArgumentException("Lists need to be of the same length.");
            }
            for (var i = 0; i < list1.Count; ++i)
            {
                MirrorObject(list1[i], list2[i]);
            }
        }
        else
        {
            targetAccessor[member.Name] = sourceAccessor[member.Name];
        }
    }
}
于 2019-09-27T18:58:20.703 回答