我有一个扩展MarshalByRefObject的远程对象。我无法在其应用程序域本身序列化该对象。原因是将状态保持在磁盘上。
我收到以下错误:
System.Runtime.Serialization.InvalidDataContractException:类型'System.Runtime.Remoting.ServerIdentity'无法序列化。请考虑使用DataContractAttribute属性对其进行标记,并使用DataMemberAttribute属性标记要序列化的所有成员。如果类型是集合,请考虑使用CollectionDataContractAttribute对其进行标记。有关其他受支持的类型,请参阅Microsoft .NET Framework文档。 at System.Runtime.Serialization.DataContract.DataContractCriticalHelper.ThrowInvalidDataContractException(String message,Type type) 在System.Runtime.Serialization.DataContract.DataContractCriticalHelper.CreateDataContract(Int32 id,RuntimeTypeHandle typeHandle,Type type) 在System.Runtime.Serialization.DataContract.DataContractCriticalHelper.GetDataContractSkipValidation(Int32 id,RuntimeTypeHandle typeHandle,Type type) 在System.Runtime.Serialization.XmlObjectSerializerContext.GetDataContract(RuntimeTypeHandle typeHandle,Type type) 在System.Runtime.Serialization.XmlObjectSerializerWriteContext.SerializeWithXsiType(XmlWriterDelegator xmlWriter,Object obj,RuntimeTypeHandle objectTypeHandle,Type objectType,Int32 declaredTypeID,RuntimeTypeHandle declaredTypeHandle,Type declaredType) 在System.Runtime.Serialization.XmlObjectSerializerWriteContext.InternalSerialize(XmlWriterDelegator xmlWriter,Object obj,Boolean isDeclaredType,Boolean writeXsiType,Int32 declaredTypeID,RuntimeTypeHandle declaredTypeHandle) 在System.Runtime.Serialization.XmlObjectSerializerWriteContext.InternalSerializeReference(XmlWriterDelegator xmlWriter,Object obj,Boolean isDeclaredType,Boolean writeXsiType,Int32 declaredTypeID,RuntimeTypeHandle declaredTypeHandle)
我的代码看起来像这样
[DataContract]
public class MyClass : MarshalByRefObject
{
[DataMember]
private int a;
[DataMember]
private bool b;
public MyClass()
{
serializer = new DataContractSerializer(typeof(MyClass));
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2202:Do not dispose objects multiple times")]
public virtual void SaveToFile(string filepath)
{
// Method to save our object to a file.
// If there is already a save in progress, bail (thread safety check)
if (SaveInProgress)
{
return;
}
SaveInProgress = true;
Stream stream = null;
XmlWriter xw = null;
try
{
stream = new FileStream(filepath, FileMode.Create, FileAccess.Write);
xw = XmlWriter.Create(stream, new XmlWriterSettings { Indent = true, Encoding = Encoding.UTF8 });
using (XmlDictionaryWriter writer = XmlDictionaryWriter.CreateDictionaryWriter(xw))
{
lock (LockObject)
{
serializer.WriteObject(writer, this);
}
}
}
finally
{
if (stream != null)
{
stream.Dispose();
}
if (xw != null)
{
xw.Dispose();
}
}
SaveInProgress = false;
}
}