在C#中克隆动态对象 [英] Cloning dynamic object in c#

查看:79
本文介绍了在C#中克隆动态对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用以下代码克隆动态对象时遇到问题:

I have a problem cloning dynamic object with the code like this:

    public void Execute(IPrepareData entity)
    {
        try
        {                
            dynamic data = entity.Primary as dynamic;
            data.PreviousInfo = deepClone(data.Info);
        }
        catch (Exception ex)
        {
            data.Errors.Add(ex.Message);
        }
    }

    private static T deepClone<T>(T obj)
    {
        if (typeof(T).IsClass || typeof(T).IsArray)
        {
            if (ReferenceEquals(obj, null))
            {
                return default(T);
            }
        }
        using (var memoryStream = new MemoryStream())
        {
            BinaryFormatter fieldFormatter = new BinaryFormatter();
            fieldFormatter.Serialize(memoryStream, obj);
            memoryStream.Position = 0;
            return (T)fieldFormatter.Deserialize(memoryStream);
        }
    }

    dynamic data;

我事先不知道实体的结构(只是它会包含Info,而我不知道info的结构),并且不会将其标记为可序列化。我需要将此信息复制到实体的先前信息部分。

I don't know the structure of entity in advance (only that it will contain Info, and I don't know the structure of info) and that it won't be marked serializable. I need to copy this info to previous info section of entity.

此代码的执行结果是fieldFormatter上的对象引用未设置为对象的实例。序列化行。

Result of execution of this code is 'Object reference not set to an instance of an object' on fieldFormatter.Serialize line.

如何检查它是否是对象的实例?

How can I check if it is an instance of an object?

可能有(很可能是)循环引用,所以我不尝试反射,因为我不确定如何处理。速度也不是问题。

There might be (most probably will be) circular references, so I am not trying reflection as I am not sure how to deal with that. Also speed is not an issue.

推荐答案

如果您不知道数据将被标记为可序列化,那么您可以' t依靠使用 BinaryFormatter

If you don't know that the data will be marked serializable, then you can't rely on using BinaryFormatter.

如果对象可能具有循环引用,则还有许多其他序列化器

If the object is likely to have circular references, a lot of other serializers are out of the question.

如果我们假定这是动态的一般情况 (而不仅仅是 ExpandoObject ),那么就无法获取有关成员的信息,因为可以在查询时发明它们。

If we assume it is the general case of dynamic (and not just ExpandoObject), then there is no way of getting information about the members, since they can be invented as they are queried.

基本上,这种情况没有很好的答案。深度克隆事物没有魔术的方法。

Basically, this scenario *has no good answer. There is no magic way to just deep clone "a thing".

这篇关于在C#中克隆动态对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆