首页 > 解决方案 > 如何在 C# 中处理不同的有效负载类型

问题描述

我来自 JavaScript/TypeScript 世界,我正在学习一些 C#,只是为了好玩。我目前正在尝试做一些我在 JS 中非常习惯做的事情,它有一个可以根据类中的变量进行更改的有效负载。所以,我尝试了以下方法:

namespace Shared.Commands
{
    public class Command
    {
        public string clientUuid { get; set; }
        public string type { get; set; }
        public dynamic payload { get; set; }
    }
}

所以,在这个例子中,我想知道哪种类型payload是基于type. 我想知道dynamic在这种情况下使用什么替代品,因为我正在查看一些文章,他们提到我应该尽可能避免使用dynamic

关键是:我对如何以任何其他方式实现这一点一无所知,并希望得到一些指导。我真的很感激任何提示或示例。

标签: c#

解决方案


一种简单的方法是将有效负载定义为对象,然后使用序列化。那里有大量的序列化程序,因此请选择最适合您的序列化程序。

public class Command
{
    public string ClientUuid { get; set; }
    public string Type { get; set; }
    public Object Payload { get; set; }

    public static void Serialize ( Command command, MemoryStream stream )
    {
        var formatter = new BinaryFormatter ();
        formatter.Serialize ( stream, command );
    }

    public static void Deserialize (out Command command, MemoryStream stream )
    {
        var formatter = new BinaryFormatter();
        command = (Command)formatter.Deserialize ( stream );
    }
}

然后,如果打字很重要,你可以做这样的事情。

public class Command<T> : Command
{
    public new T Payload
    {
        get
        {
            return (T)base.Payload;
        }
        set
        {
            base.Payload = (T)value;
        }
    }
}

并像这样使用它。

public void Usage ()
{
    Command<YourObject> obj = new Command<YourObject> () {
        Payload = new YourObject ()
    };

    using ( var stream = new MemoryStream () )
    {
        Command.Serialize ( obj, stream );

        // do something with serialized data in stream;
    }          
}

推荐阅读