无法从“System.ReadOnlyMemory<byte>”转换为“byte[]”

2024-03-05 15:51:28 浏览数 (2)

1、问题复现

RabbitMQ的官方示例:RabbitMQ消费端(接收端)获取消息时抛出异常,具体代码如下

代码语言:javascript复制
var consumer = new EventingBasicConsumer(channel);
consumer.Received  = (model, ea) =>
{
    var body = ea.Body;
    var message = Encoding.UTF8.GetString(body); // <------错误点
    Console.WriteLine(" [x] Received {0}", message);
};

2、解决办法

查看定义可以看到Encoding.UTF8.GetString重载的方法有多个,参数为字节数组或其指针或只读的字节跨度。

RabbitMQ更新API的地址:https://github.com/rabbitmq/rabbitmq-dotnet-client/commit/8bf93082fd2c18bbd6adff260d38a6fd34d6840b

接下来说下解决办法

① ToArrary()

示例是之前的示例,现在官方示例已更正,最新示例地址:https://www.rabbitmq.com/tutorials/tutorial-one-dotnet.html

代码语言:javascript复制
var consumer = new EventingBasicConsumer(channel);
consumer.Received  = (model, ea) =>
{
    var body = ea.Body.ToArray(); // 将内存区域的内容复制到一个新的数组中
    var message = Encoding.UTF8.GetString(body);
    Console.WriteLine(" [x] Received {0}", message);
};

② Span

代码语言:javascript复制
var consumer = new EventingBasicConsumer(channel);
consumer.Received  = (model, ea) =>
{
    var body = ea.Body.Span; // 从内存区域获取一个跨度
    var message = Encoding.UTF8.GetString(body);
    Console.WriteLine(" [x] Received {0}", message);
};
以上就是无法从“System.ReadOnlyMemory<byte>”转换为“byte[]”的介绍,做此记录,如有帮助,欢迎点赞关注收藏!

0 人点赞