Assembly asm = Assembly.LoadFrom(@"E:\Alarm1\alarm1.dll"); Type t = asm.GetType("Alarm"); object o = Activator.CreateInstance(t);IFormatter ft = new SoapFormatter(); Stream s = new FileStream("Form2.xml",FileMode.Create ,FileAccess.Write,FileShare.None ); ft.Serialize(s,o); s.Close();
用Deserialize(Stream)反序列化啊,反序列化之后就是你的对象object o = ft.Deserialize(s);Type t = o.GetType();就可以得到类型,你可以通过判断类型来做你要的操作
好像不行啊,object o = ft.Deserialize(s);运行时报错:未处理的“System.Runtime.Serialization.SerializationException”类型的异常出现在 system.runtime.serialization.formatters.soap.dll 中其他信息:Parse Error, no assembly associated with Xml key a1:http://schemas.microsoft.com/clr/nsassem/Alarm1%2C%20Version%3D1.0.1227.28352%2C%20Culture%3Dneutral%2C%20PublicKeyToken%3Dnull Alarm
To: qqchen79(知秋一叶 [MS MVP])我想实现:把panel序列化,然后再反序列化(当然,panel以及上面的控件都实现了接口ISerializable)对于集合Controls的序列化,反序列化,不知道你有没有什么建议?下面是我做的,但反序列化有问题:public void GetObjectData(SerializationInfo info,StreamingContext text) { int i = 0; foreach(Control c in Controls) { info.AddValue( "Control" + i.ToString() ,c ); ++i; } info.AddValue("ControlCount",this.Controls.Count ); }public myPanel(SerializationInfo info,StreamingContext text) { int iCount = 0;
iCount = (int)info.GetValue("ControlCount",typeof(int)); for(int i = 0;i < iCount;++i) { Control c = (Control)info.GetValue("Control" + i.ToString(),typeof(Control)); //this.Controls.Add(c); //报错,错误见下面 } }未处理的“System.Reflection.TargetInvocationException”类型的异常出现在 mscorlib.dll 中其他信息:Exception has been thrown by the target of an invocation.
得到这个Type
反序列化怎么使用他呢?
Type t = asm.GetType("Alarm");
object o = Activator.CreateInstance(t);IFormatter ft = new SoapFormatter();
Stream s = new FileStream("Form2.xml",FileMode.Create ,FileAccess.Write,FileShare.None );
ft.Serialize(s,o);
s.Close();
http://expert.csdn.net/Expert/topic/1664/1664902.xml?temp=.5007898主要问题是Deserialize会使用CLR的Assembly Probe来寻找Assembly,在你的环境下这种方式是找不到Alarm的。你有两个选择:
1. 使用我在上一个贴子里提到的方法,写一个SerializationBinder.
2. 接受当前AppDomain的AssemblyResolve事件,然后用Assembly.LoadFrom自己加载Alarm程序集并返回。其实在程序中最好避免使用LoadFrom和绝对路径,最好能够把Assembly放在程序Probe路径当中,让CLR自己能够找到。
2. 接受当前AppDomain的AssemblyResolve事件,然后用Assembly.LoadFrom自己加载Alarm程序集并返回。上面这个事件在哪里?你怎么都是凌晨上网?
currentDomain.AssemblyResolve += new ResolveEventHandler(MyResolveEventHandler);
static Assembly MyResolveEventHandler(object sender, ResolveEventArgs args) {}
{
int i = 0;
foreach(Control c in Controls)
{
info.AddValue( "Control" + i.ToString() ,c );
++i;
}
info.AddValue("ControlCount",this.Controls.Count );
}public myPanel(SerializationInfo info,StreamingContext text)
{
int iCount = 0;
iCount = (int)info.GetValue("ControlCount",typeof(int));
for(int i = 0;i < iCount;++i)
{
Control c = (Control)info.GetValue("Control" + i.ToString(),typeof(Control));
//this.Controls.Add(c); //报错,错误见下面
}
}未处理的“System.Reflection.TargetInvocationException”类型的异常出现在 mscorlib.dll 中其他信息:Exception has been thrown by the target of an invocation.