How to serialize/deserialize an object loaded from another assembly?

前端 未结 2 2115
我在风中等你
我在风中等你 2020-12-08 08:45

I want to serialize/deserialize an object that has been instantiated by another object loaded from an assembly:

Interfaces.cs (from a referenced assembly, Interfaces

2条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-08 09:32

    Do you want to (de)serialize using binary format? If no you may use the following:

    P.S. This is not an solution but some kind of workaround.

    Some assembly

    public interface ISomeInterface { ISettings Settings { get; set; } }

    public interface ISettings : ISerializable
    {
        DateTime StartDate { get; }
    }
    
    public class SerializeHelper
    {
        public static void Serialize(string path, T item)
        {
            var serializer = new XmlSerializer(typeof(T));
            using (TextWriter textWriter = new StreamWriter(path, false, Encoding.UTF8))
            {
                serializer.Serialize(textWriter, T item);
            }
        }
    }
    
    SerializeHelper.Serialize(@"%temp%\sample.xml", instanceOfISomeInterface);
    

    Some other assembly

    public interface ISomeOtherInterface
    {
    ISettings Settings { get; set; }
    }
    
    public class DeSerializeHelper
    {
        public static T Deserialize(string path)
        {
       T instance = default(T);
       var serializer = new XmlSerializer(typeof(TestData));
       using (TextReader r = new StreamReader(path, Encoding.UTF8))
       {
          instance = (T)serializer.Deserialize(r);
       }
       return instance;
        }
    }
    
    ISomeOtherInterface instance = DeSerializeHelper.Deserialize(@"%temp%\sample.xml")
    

提交回复
热议问题