BinaryFormatter序列化在序列化期间不包括datatable.defaultview.sort属性

时间:2018-07-24 11:52:48

标签: c# .net serialization binary-serialization

我有一个具有多个属性的类,其中一些属性类型为datatable

我正在使用BinaryFormatter创建类的克隆副本,它可以正常工作,但是使用某些值设置的datatable.defaultview.sort不能像克隆对象中那样应付。 这是示例代码

   public static void Main(string[] args)
    {
        TestCloneDatatable();
    }


    private static void TestCloneDatatable()
    {
        DataTable datatatable = new DataTable();
        datatatable.Columns.Add("ID", typeof(int));
        datatatable.Columns.Add("AddressLine1", typeof(string));

        for (int i = 0; i < 10; i++)
        {
            datatatable.Rows.Add(i, string.Concat("test ", i));
        }

        datatatable.DefaultView.Sort = "AddressLine1 ASC";

        Test test = new Test();
        test.ID = 1;
        test.Name = "my Name";
        test.Addresss = datatatable;


        Test testClone = test.Clone();

        string sort = testClone.Addresss.DefaultView.Sort; //here it is empty, I need "AddressLine1 ASC" should be there 

    }

    [SerializableAttribute]
    public class Test
    {
        public int ID { get; set; }
        public string Name { get; set; }
        public DataTable Addresss { get; set; }


        public Test Clone()
        {

            Test result = DeepCopy<Test>(this);
            return result;
        }

        protected T DeepCopy<T>(T item)
        {
            BinaryFormatter formatter = new BinaryFormatter();
            MemoryStream stream = new System.IO.MemoryStream();
            formatter.Serialize(stream, item);
            stream.Seek(0, SeekOrigin.Begin);
            T result = (T)formatter.Deserialize(stream);
            stream.Close();
            return result;
        }

    } 

0 个答案:

没有答案