在下面的代碼,當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;
}
}
}
}