[英]How to simulate the printing of object like in C# Interactive Console?
沒有這樣的構建工具,但您可以將其轉換為 Json。 您的示例的問題對於 ConcurrentDictionary 來說並不那么容易。
重要的提示:
This only will work for Newtonsoft
and .NET 6.0
since System.Text.Json
does not provide a cast for serialize to JSON ConcurrentDictionary
and this also don't work for Newtonsoft
in .NET Framework
如何序列化為 JSON 字符串 ConcurrentDictionary?
從 Nugget 導入Newtonsoft.Json
using Newtonsoft.Json;
到文件頭部的引用
ConcurrentDictionary<(int,int), (double,int)> scoreDir = new ConcurrentDictionary<(int,int), (double,int)>();
scoreDir.TryAdd((1,2),(0.9,3));
string jsonString = JsonConvert.SerializeObject(scoreDir);
Console.WriteLine(jsonString);
回報:
{"(1, 2)":{"Item1":0.9,"Item2":3}}
在評論部分感謝@Hans Passant 。
In Visual Studio, after installing the Nuget package Microsoft.CodeAnalysis.CSharp.Scripting
, the static function Microsoft.CodeAnalysis.CSharp.Scripting.Hosting.CSharpObjectFormatter.Instance.FormatObject()
can be used to mimic the same output as C# Interactive Console.
這是有效的代碼:
using System;
using System.IO;
using System.Collections.Concurrent;
namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
var scoreDir = new ConcurrentDictionary<(int, int), (double, int)>();
scoreDir.TryAdd((1, 2), (0.9, 3));
var res = Microsoft.CodeAnalysis.CSharp.Scripting.Hosting.CSharpObjectFormatter.Instance.FormatObject(scoreDir);
Console.WriteLine(res);
}
}
}
結果:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.