无法实现已区分的联合并将其序列化

时间:2019-02-15 08:13:23

标签: serialization .net-core discriminated-union

你好,我正在尝试使用discriminated union创建类的层次结构,看来我无法序列化它们。我不断收到此错误:

Newtonsoft.Json.JsonSerializationException: 'Self referencing loop detected for property 'AsRun' with type 'MsgPattern.Message+Run'. Path ''.'

基类

[Serializable]
    public abstract partial class Message {
        public enum Type {
            WALK = 0,
            RUN = 1
        }
        protected abstract Type Discriminator { get; }
        public Type Kind => this.Discriminator;

        internal static Message Create(string data) {
            var message = JsonConvert.DeserializeObject<Message>(data);
            switch (message.Kind) {
                case Type.RUN:message= message.AsRun;break;
                case Type.WALK:message= message.AsWalk;break;
            }
            return message;
        }
        [JsonIgnore]
        public bool IsWalk => this.Kind==Type.Walk;
        [JsonIgnore]
        public bool IsRun => this.Kind==Type.Run;
        [JsonIgnore]
        public Message.Walk AsWalk => this as Message.Walk;
        [JsonIgnore]
        public Message.Run AsRun => this as Message.Run;


    }

遗弃

partial class Message {

        public class Run : Message {
            protected override Type Discriminator => Type.RUN;
            public string Location { get; set; }
            public int Speed { get; set; }
        }
    }

partial class Message {

        public class Walk : Message {
            protected override Type Discriminator => Type.WALK;
            public int Gait { get; set; }
            public bool IsJogging { get; set; }
        }
    }

用法

class Program {


   static void Main(string[] args) {
        Message.Run run = new Message.Run { Location = "asa", Speed = 33 };
        string data = JsonConvert.SerializeObject(run);
        Message msg=Message.Create(data);
    }
}

我将通过json收到这些类型的消息,并且我希望能够根据其type进行操作。我不明白为什么我不能序列化它们。

PS ,我知道这是一个自引用循环,但是我需要那些As[something]Is[Something]字段。

0 个答案:

没有答案