开发者

How to serialize an object inside of a dll?

So, I've a project that loads dlls on runtime and I'm using reflection and an interface to create the dlls.

I created a user control referenced as dll (at runtime) that has a List that needs to be serialized. It serializes the project right, but when I try to loa开发者_如何学JAVAd it I can't deserialize it.

now, I tested this usercontrol on another project that references the user control as project and it worked well.

Here's my code:

    static public object SerializeLoad(string sFilename)
    {
        try
        {
            object _object = null;
            Stream stream = File.Open(sFilename, FileMode.Open);
            //BinaryFormatter bformatter = new BinaryFormatter();
            XmlSerializer bformatter = new XmlSerializer(typeof(ElementTodo), "ToDo");

            //_object = (_object.GetType())bformatter.Deserialize(stream);
            _object = bformatter.Deserialize(stream);
            stream.Close();
            return _object;
        }
        catch
        {
            return null;
        }
    }

I tried both, binary and xml and both through "There is an error in XML document (2, 2)." Any ideas why is this?


The generated XML is as follows:

  <?xml version="1.0"?> 
  <ArrayOfElementTodo xmlns:xsi="w3.org/2001/XMLSchema-instance"; xmlns:xsd="w3.org/2001/XMLSchema"; xmlns="ToDo"> 
      <ElementTodo Title="a" content="aa" isDone="false" /> 
      <ElementTodo Title="b" content="bb" isDone="false" /> 
      <ElementTodo Title="c" content="cc" isDone="false" /> 
      <ElementTodo Title="d" content="dd" isDone="false" /> 
  </ArrayOfElementTodo>


The reason is that in order to be able to deserialize an object, the type of the object must be available since .NET is a statically typed environment. (Every instance which lives in your program must have a type with a list of its members etc.)

Or, you could use C# 4 dynamic to deserialize arbitrary XML (1, 2).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜