c# - How to assign a variable with .ConvertToString() method in C# to parse the message?
问题描述
I am looking to learn how to assign a name to the newly converted string and then parse that string based on
string[] separatingStrings = { ",", "<<", ">>" };
string[] messages = message.Split(separatingStrings);
Console.WriteLine($"{messages.Length} substrings in text:");
below contains the var message
converted to a string.
What is the name of the string so I can parse it and output it into unity debug.log
?
private void ReceiveMessageLoop()
{
while (true)
{
var message = new NetMQMessage();
if (!_socket.TryReceiveMultipartMessage(MessageCheckRate, ref message, 2)) continue;
_messageSubject.OnNext(message);
Console.WriteLine($"0:{message[0].ConvertToString()} 1:{message[1].ConvertToString()}");
//Console.WriteLine(message);
}
}
解决方案
You can't declare a variable in a string interpolation expression.
Console.WriteLine($"{string bar = "hello"}"); // This gives error CS1525: Invalid expression term 'string'
So instead, declare it outside the string interpolation, and you can assign it in the interpolation expression with an assignment expression.
string bar;
Console.WriteLine($"{bar = "hello"}"); // This is OK
Console.WriteLine(bar);
Your specific example:
string msg0, msg1;
Console.WriteLine($"0:{msg0 = message[0].ConvertToString()} 1:{msg1 = message[1].ConvertToString()}");
Console.WriteLine(msg0);
Console.WriteLine(msg1);
Bonus tip: You can, however, use an out
variable declaration in an interpolation expression. The scope is the same as the line (not somehow local to the interpolation expression). e.g.:
class Program
{
static string Test(out string x, string y) {
return x = y;
}
static void Main(string[] args)
{
Console.WriteLine($"{Test(out string bar, "Hello")}");
Console.WriteLine(bar);
}
}
推荐阅读
- bazel - Bazel run - 传递主要参数
- url - Asp.Net Core Routing 使用参数转换器并取决于文化
- php - “找不到数据源名称”的建议解决方案不起作用
- python - 如何使用矩阵数学来解决调度问题?
- javascript - 从 JSON 对象列表中删除对象类型
- java - 如何在 Java 中获取 BlockingQueue 的内存大小
- jwt - 令人惊讶的是,我得到了相同的 access_token 和 id_token 代码
- android - 单击按钮时重复执行操作
- python-3.x - 熊猫在上一步滚动窗口
- c - 从 uchar* 转换为 uint* 会产生不可预测的结果