列出<object>和深层副本

时间:2018-04-24 21:29:11

标签: c# list object clone deep-copy

我有一个具有值类型和一些List<Object>成员的类。该类实现了IClonable接口,并实现了Clone()GetHashCode()。在Clone()方法中,我使用MemberwiseClone()方法来克隆值类型。

我也在Object(我们称之为Person)类中进行了相同的编码。我想在referrer类的Clone()方法中调用该类的Clone()方法。但由于此类的类型为Object,我无法调用它的Clone()方法。

我无法在此Object Person,因为Object的类型在运行时会发生变化。有时候,“人”有时会“订购”。

以下是示例代码:

public class Person : IClonable
{
    public string name = "Name";
    public string surname = "Surname";

    public override Person Clone()
    {
        Person p = this.MemberwiseClone();
    }
}

public class Order : IClonable
{
    public string name = "OrderName";
    public int orderId = 1;

    public override Order Clone()
    {
        Person p = this.MemberwiseClone();
    }
}

public class List : IClonable
{
    public string listname = "ListName";
    List<object> objectList = new List<object>();

    public override List Clone()
    {
        List l = this.MemberwiseClone(); //This clones value types

        List<object> copyObjectList = new List(object);

        foreach(Object o in objectList)
        {
            Object co = o.Clone(); //I want something like this
            copyObjectList.Add(co);
        }

        l.objectList = copyObjectList;

        return l;
    }
}

1 个答案:

答案 0 :(得分:0)

我不确定我是否完全明白你的问题...但是你是不是喜欢这样的事情?

import pytest

def test_my_method_error_message():
    offending_key = 'test'
    data = {offending_key: 'whatever'}
    with pytest.raises(SpecFormatException) as excinfo:
        my_method(data)
        assert data in str(excinfo.value)