ZetCode

C# Spectre.Console

最后修改于 2023 年 7 月 5 日

在本文中,我们将展示如何使用 Spectre.Console 库创建 C# 控制台应用程序。

Spectre.Console 是一个用于创建控制台应用程序的 .NET 库。 它支持终端文本中的颜色和样式。 它允许创建终端小部件,例如网格、表格或树。 它甚至有一些基本的图表。

$ dotnet add package Spectre.Console

我们将库添加到项目中。

Spectre.Console 颜色

我们可以使用 AnsiConsole.MarkupAnsiConsole.MarkupLine 方法编写彩色文本。

Program.cs
using Spectre.Console;

AnsiConsole.MarkupLine("[steelblue]an old falcon[/]");
AnsiConsole.MarkupLine("[#ff0000]an old falcon[/]");
AnsiConsole.MarkupLine("[rgb(25,0,255)]an old falcon[/]");

AnsiConsole.MarkupLine("[bold gray on blue]an old falcon[/]");
AnsiConsole.MarkupLine("[bold steelblue on white]an old falcon[/]");

该示例用不同的颜色书写文本。

AnsiConsole.MarkupLine("[steelblue]an old falcon[/]");
AnsiConsole.MarkupLine("[#ff0000]an old falcon[/]");
AnsiConsole.MarkupLine("[rgb(25,0,255)]an old falcon[/]");

文本的颜色可以用不同的方式指定。 我们可以使用名称、十六进制和 RGB 代码。

AnsiConsole.MarkupLine("[bold gray on blue]an old falcon[/]");
AnsiConsole.MarkupLine("[bold steelblue on white]an old falcon[/]");

我们也可以更改背景颜色。

Spectre.Console 样式

我们有预定义的样式,例如粗体、斜体和删除线。

Program.cs
using Spectre.Console;

AnsiConsole.MarkupLine("[dim]an old falcon[/] ");
AnsiConsole.MarkupLine("[italic]an old falcon[/] ");
AnsiConsole.MarkupLine("[bold]an old falcon[/] ");
AnsiConsole.MarkupLine("[underline]an old falcon[/] ");
AnsiConsole.MarkupLine("[bold dim]an old falcon[/] ");
AnsiConsole.MarkupLine("[dim italic]an old falcon[/] ");
AnsiConsole.MarkupLine("[bold italic]an old falcon[/] ");
AnsiConsole.MarkupLine("[dim underline]an old falcon[/] ");
AnsiConsole.MarkupLine("[strikethrough]an old falcon[/] ");
AnsiConsole.MarkupLine("[bold strikethrough]an old falcon[/] ");
AnsiConsole.MarkupLine("[italic strikethrough]an old falcon[/] ");

在该程序中,我们对文本应用了各种样式。

AnsiConsole.MarkupLine("[italic]an old falcon[/] ");

这行文本以斜体显示。

AnsiConsole.MarkupLine("[dim italic]an old falcon[/] ");

样式可以组合使用。

Spectre.Console 规则

规则是一条带有标题的水平线。 标题可以对齐。 该规则用作装饰。

Program.cs
using Spectre.Console;

var rule = new Rule("[steelblue]Python[/]");
rule.LeftJustified();
AnsiConsole.Write(rule);

AnsiConsole.WriteLine(@"Python is a general-purpose, dynamic, object-oriented
programming language. The design purpose of the Python language
emphasizes programmer productivity and code readability.");

var rule2 = new Rule("[skyblue1]F#[/]");
rule2.Centered();
AnsiConsole.Write(rule2);

AnsiConsole.WriteLine(@"F# is a universal programming language for writing succinct,
robust and performant code.");

var rule3 = new Rule("[indianred]Go[/]");
rule3.RightJustified();
AnsiConsole.Write(rule3);

AnsiConsole.WriteLine(@"Go is an open source programming language that makes it easy to
build simple, reliable, and efficient software. Go is a statically
typed, compiled programming language.");

在该程序中,我们使用了三个规则。

var rule = new Rule("[steelblue]Python[/]");
rule.LeftJustified();
AnsiConsole.Write(rule);

我们创建第一个蓝色。 标题具有 steelblue 颜色,并向左对齐。

Spectre.Console 面板

面板是一个小部件,它在渲染框中组织文本。

Program.cs
using Spectre.Console;

var txt1 = @"Python is a general-purpose, dynamic, object-oriented
programming language. The design purpose of the Python language
emphasizes programmer productivity and code readability.";

var header1 = new PanelHeader("Python");
var pnl1 = new Panel(txt1);
pnl1.Header = header1;

AnsiConsole.Write(pnl1);

var txt2 = @"F# is a universal programming language for writing succinct,
robust and performant code.";

var header2 = new PanelHeader("F#");
var pnl2 = new Panel(txt2);
pnl2.Header = header2;

AnsiConsole.Write(pnl2.AsciiBorder().HeaderAlignment(Justify.Center));

该程序创建了两个面板。

var header1 = new PanelHeader("Python");
var pnl1 = new Panel(txt1);
pnl1.Header = header1;

AnsiConsole.Write(pnl1);

面板由标题和框组成。

AnsiConsole.Write(pnl2.AsciiBorder().HeaderAlignment(Justify.Center));

可以修改面板边框和标题对齐方式。

Spectre.Console JSon.Text

Spectre.Console 可以漂亮地打印 JSON 数据。

$ dotnet add package Spectre.Json.Text

我们需要添加 Spectre.Json.Text 包。

Program.cs
using Spectre.Console;
using Spectre.Console.Json;

var client = new HttpClient();
var content = await client.GetStringAsync("http://webcode.me/users.json");

var json = new JsonText(content);

AnsiConsole.Write(
       new Panel(json)
           .Header("Users")
           .Collapse()
           .RoundedBorder()
           .BorderColor(Color.CadetBlue));

在该示例中,我们从 Web 资源检索 JSON 数据,并在面板中显示它。

var client = new HttpClient();
var content = await client.GetStringAsync("http://webcode.me/users.json");

使用 HttpClient,我们检索 JSON 数据。

var json = new JsonText(content);

我们将数据传递到 JsonText 中。

AnsiConsole.Write(
  new Panel(json)
      .Header("Users")
      .Collapse()
      .RoundedBorder()
      .BorderColor(Color.CadetBlue));

JsonText 在面板中呈现。

Spectre.Console 网格

网格是一个小部件,它在一组列和行中显示数据。 还有一个更复杂的小部件叫做表格。

$ dotnet add package Binance.Net

对于此示例,我们需要 Binance.Net 库。

Program.cs
using Binance.Net.Clients;
using Spectre.Console;

using var client = new BinanceClient();

var ires = await client.SpotApi.ExchangeData.GetTickerAsync("LTCBUSD");
var data = ires.Data;

var grid = new Grid()
       .AddColumn(new GridColumn().NoWrap().PadRight(4))
       .AddColumn()
       .AddRow("Last price", $"{data.LastPrice}")
       .AddRow("Open price", $"{data.OpenPrice}")
       .AddRow("High price", $"{data.HighPrice}")
       .AddRow("Low price", $"{data.LowPrice}")
       .AddRow("Price change", $"{data.PriceChange}")
       .AddRow("Price change (%)", $"{data.PriceChangePercent}");

AnsiConsole.Write(grid);

在该程序中,我们获取 LTCBUSD 符号的行情数据,并在网格小部件中显示它。

$ dotnet run
Last price          91.27000000
Open price          91.58000000
High price          92.94000000
Low price           89.89000000
Price change        -0.31000000
Price change (%)    -0.338

Spectre.Console 表格

更复杂的表格数据可以在 Table 小部件中显示。

Program.cs
using Binance.Net.Clients;
using Spectre.Console;

using var client = new BinanceClient();

var ires = await client.SpotApi.ExchangeData.GetTickerAsync("LTCBUSD");
var data = ires.Data;

var table = new Table()
          .Border(TableBorder.Ascii)
          .BorderColor(Color.SteelBlue)
          .AddColumn(new TableColumn("OHLC").LeftAligned())
          .AddColumn(new TableColumn("Value").RightAligned())
          .AddRow("Last price", $"{data.LastPrice}")
          .AddRow("Open price", $"{data.OpenPrice}")
          .AddRow("High price", $"{data.HighPrice}")
          .AddRow("Low price", $"{data.LowPrice}")
          .AddRow("Price change", $"{data.PriceChange}")
          .AddRow("Price change (%)", $"{data.PriceChangePercent:0.00000000}");

AnsiConsole.Write(table);

我们获取 LTCBUSD 的行情数据,并在表格中显示它。

$ dotnet run
+--------------------------------+
| OHLC             |       Value |
|------------------+-------------|
| Last price       | 91.42000000 |
| Open price       | 92.22000000 |
| High price       | 92.94000000 |
| Low price        | 89.89000000 |
| Price change     | -0.80000000 |
| Price change (%) | -0.86700000 |
+--------------------------------+

来源

https://spectreconsole.net

在本文中,我们使用了 Spectre.Console 在 C# 中创建控制台应用程序。

作者

我叫 Jan Bodnar,我是一位充满激情的程序员,拥有丰富的编程经验。 自 2007 年以来,我一直在撰写编程文章。 迄今为止,我已经撰写了超过 1,400 篇文章和 8 本电子书。 我拥有超过十年的编程教学经验。

列出所有 C# 教程