【发布时间】:2011-01-31 16:48:47
【问题描述】:
我正在尝试使用System.Dynamic.ExpandoObject,以便可以在运行时动态创建属性。稍后,我需要传递这个对象的一个实例,并且使用的机制需要序列化。
当然,当我尝试序列化我的动态对象时,我得到了异常:
System.Runtime.Serialization.SerializationException 未处理。
程序集“System.Core, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089”中的类型“System.Dynamic.ExpandoObject”未标记为可序列化。
我可以序列化 ExpandoObject 吗?是否有另一种方法来创建可序列化的动态对象?也许使用DynamicObject 包装器?
我创建了一个非常简单的 Windows 窗体示例来复制错误:
using System;
using System.Windows.Forms;
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using System.Dynamic;
namespace DynamicTest
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
dynamic dynamicContext = new ExpandoObject();
dynamicContext.Greeting = "Hello";
IFormatter formatter = new BinaryFormatter();
Stream stream = new FileStream("MyFile.bin", FileMode.Create,
FileAccess.Write, FileShare.None);
formatter.Serialize(stream, dynamicContext);
stream.Close();
}
}
}
【问题讨论】:
-
没有实现手动序列化例程,我倾向于说如果它没有标记
Serializable那么,不,很简单。
标签: c# .net serialization dynamic expandoobject