在下面的代码,当SerializeToJson()
方法被调用时,我收到WriteObject()
以下异常:从另一个应用程序域返回的对象是否可以在调用域中序列化?
远程处理上找不到类型字段'__identity“System.MarshalByRefObject”
是什么我试图做可能吗?我有点不熟悉应用程序域及其相关事物(透明代理等)。我可以在当前的应用程序域中成功序列化我的TestClass,但我不明白为什么它不在这里工作。感谢您的期待。
using System;
using System.IO;
using System.Reflection;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Json;
namespace ConsoleApplication6
{
public class BaseClass : MarshalByRefObject { }
public class RemoteClass : BaseClass
{
public TestClass DoIt()
{
return new TestClass { Prop1 = DateTime.Now, Prop2 = 1234 };
}
}
[DataContract]
public class TestClass : MarshalByRefObject
{
public TestClass() { }
public TestClass(TestClass tc)
{
Prop1 = tc.Prop1;
Prop2 = tc.Prop2;
}
[DataMember]
public DateTime Prop1 { get; set; }
[DataMember]
public int Prop2 { get; set; }
}
class Program
{
static void Main(string[] args)
{
var appDomain = AppDomain.CreateDomain("myappdomain");
var remoteClass = (RemoteClass)appDomain.CreateInstanceAndUnwrap(Assembly.GetExecutingAssembly().FullName, typeof(RemoteClass).FullName);
var returnedTestClass = remoteClass.DoIt();
Console.WriteLine(SerializeToJson(returnedTestClass));
}
private static string SerializeToJson(object obj)
{
try
{
using (var stream = new MemoryStream())
{
var serializer = new DataContractJsonSerializer(obj.GetType());
serializer.WriteObject(stream, obj);
stream.Position = 0;
using (var streamReader = new StreamReader(stream))
{
return streamReader.ReadToEnd();
}
}
}
catch (Exception e)
{
// Error: Remoting cannot find field '__identity' on type 'System.MarshalByRefObject'.
Console.WriteLine(e.Message);
return string.Empty;
}
}
}
}