c# - 如何在 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
。
关键是:我对如何以任何其他方式实现这一点一无所知,并希望得到一些指导。我真的很感激任何提示或示例。
解决方案
一种简单的方法是将有效负载定义为对象,然后使用序列化。那里有大量的序列化程序,因此请选择最适合您的序列化程序。
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;
}
}
推荐阅读
- r - 在 R 中使用傅立叶变换进行插值
- python - Django 项目 celery 和 django-filter 导致错误
- ascii - Arial 字体斑马打印机不打印零字符
- javascript - Python 应用程序只发出一次 - 实时聊天应用程序
- c++ - 关于 Stroustrup C++ 书籍的 auto 和 {}-lists 问题
- c++ - 迭代二维向量时发生运行时错误
- html - 两个 div 并排,一个响应式
- html - 隐藏第二个元素,直到第一个元素完成动画 - CSS 关键帧
- python - “raise JSONDecodeError("Expecting value", s, err.value) from None" 我正在尝试读取和写入 json 文件
- oracle - 如何找出导致我的 Oracle 事务因等待类集群而挂起的原因?