在以下代码中,调用SerializeToJson()方法时,我在WriteObject()上收到以下异常:


  远程无法在类型'System.MarshalByRefObject'上找到字段'__identity'


我正在尝试做些什么?我对应用程序域及其相关内容(透明代理等)不熟悉。我可以在当前应用程序域中成功地序列化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;
            }
        }
    }
}

最佳答案

对于.NET Remoting,没有必要将[DataContract]MarshalByRefObject混合使用。就像使用MarshalByRefObject一样使用RemoteClass

09-18 11:04