.NET 帮助

C# 打印到控制台(开发人员操作指南)

发布 2024年四月3日
分享:

向控制台打印是 C# 编程的一个基本方面,它允许开发人员显示信息、与用户交互并调试程序。在这篇综合文章中,我们将探讨各种方法来 打印到控制台 C# 中的基本输出、格式化和高级技术。

基本控制台输出

在 C# 中打印到控制台的最直接方法是使用 Console 类的 WriteLine 方法。该方法向标准输出流中写入一行文本,后面跟一个换行符。

using System;

class Program
{
    public static void Main()
    {
        Console.WriteLine("Hello World, Welcome to C#!");
    }
}
using System;

class Program
{
    public static void Main()
    {
        Console.WriteLine("Hello World, Welcome to C#!");
    }
}
Imports System

Friend Class Program
	Public Shared Sub Main()
		Console.WriteLine("Hello World, Welcome to C#!")
	End Sub
End Class
VB   C#

在这里,Console.WriteLine 语句输出 "你好世界,欢迎使用 C#!"到控制台。Console.WriteLine "方法会自动添加一个换行符,从而使每个后续输出都显示在新行上。

Console.Write 用于内联输出

如果要打印文本而不转到下一行,可以使用 Console 类的 Write 方法。这对于单行内联或格式化输出非常有用。

using System;

class Program
{
    public static void Main()
    {
        Console.Write("Hello, ");
        Console.Write("C#!");
    }
}
using System;

class Program
{
    public static void Main()
    {
        Console.Write("Hello, ");
        Console.Write("C#!");
    }
}
Imports System

Friend Class Program
	Public Shared Sub Main()
		Console.Write("Hello, ")
		Console.Write("C#!")
	End Sub
End Class
VB   C#

在本例中,第一行是 "Hello",第二行是 "C#"。!第二行的"...... "被打印在同一行上,因为 Console.Write 不会添加新行字符。这是它与上文讨论的 Console.WriteLine 方法的唯一区别。

输出格式化

C# 提供了各种格式化选项来控制数据在控制台应用程序中的显示方式。Console.WriteLine "方法支持使用格式指定器进行复合格式化。

using System;

class Program
{
    public static void Main()
    {
        string name = "John";
        int age = 25;
        Console.WriteLine("Name: {0}, Age: {1}", name, age);
    }
}
using System;

class Program
{
    public static void Main()
    {
        string name = "John";
        int age = 25;
        Console.WriteLine("Name: {0}, Age: {1}", name, age);
    }
}
Imports System

Friend Class Program
	Public Shared Sub Main()
		Dim name As String = "John"
		Dim age As Integer = 25
		Console.WriteLine("Name: {0}, Age: {1}", name, age)
	End Sub
End Class
VB   C#

这里,{0}{1} 是 "姓名 "和 "年龄 "值的占位符。这将导致格式化输出 "姓名:John, 年龄:25":约翰,年龄:25"。

使用字符串插值

字符串插值是 C# 6 中引入的一种简洁的字符串格式化方法。它允许你将表达式直接嵌入字符串字面量中。

using System;

class Program
{
    public static void Main()
    {
        string name = "Alice";
        int age = 30;
        Console.WriteLine($"Name: {name}, Age: {age}");
    }
}
using System;

class Program
{
    public static void Main()
    {
        string name = "Alice";
        int age = 30;
        Console.WriteLine($"Name: {name}, Age: {age}");
    }
}
Imports System

Friend Class Program
	Public Shared Sub Main()
		Dim name As String = "Alice"
		Dim age As Integer = 30
		Console.WriteLine($"Name: {name}, Age: {age}")
	End Sub
End Class
VB   C#

$符号表示字符串插值,$符号内的表达式表示字符串插值。{}** 会被评估并插入字符串中。

控制台输出:姓名爱丽丝,年龄:30

显示当前日期

下面,我们将探讨如何使用 Console.WriteLine 方法将当前数据打印到控制台。这是调试、记录或向用户提供实时反馈的常用方法。

using System;

class Program
{
    public static void Main()
    {
        // Assuming you have some date to display, let's say the current date
        DateTime currentDate = DateTime.Now;

        // Using Console.WriteLine to print the current date to the console
        // before/after some action which needs debugging to analyze the problem
        Console.WriteLine($"Current Date: {currentDate}");
    }
}
using System;

class Program
{
    public static void Main()
    {
        // Assuming you have some date to display, let's say the current date
        DateTime currentDate = DateTime.Now;

        // Using Console.WriteLine to print the current date to the console
        // before/after some action which needs debugging to analyze the problem
        Console.WriteLine($"Current Date: {currentDate}");
    }
}
Imports System

Friend Class Program
	Public Shared Sub Main()
		' Assuming you have some date to display, let's say the current date
		Dim currentDate As DateTime = DateTime.Now

		' Using Console.WriteLine to print the current date to the console
		' before/after some action which needs debugging to analyze the problem
		Console.WriteLine($"Current Date: {currentDate}")
	End Sub
End Class
VB   C#

在本例中,我们利用 DateTime.Now 属性获取当前日期和时间。然后使用 Console.WriteLine 语句将此信息打印到控制台。结果就是简洁明了地显示当前日期。

控制台输入

除了输出,控制台还经常用于用户输入。使用 Console.ReadLine 方法可以读取用户输入的一行文本。

using System;

class Program
{
    public static void Main(string args [])
    {
        Console.Write("Enter your name: ");
        string variable = Console.ReadLine();
        Console.WriteLine($"Hello, {variable}!");
    }
}
using System;

class Program
{
    public static void Main(string args [])
    {
        Console.Write("Enter your name: ");
        string variable = Console.ReadLine();
        Console.WriteLine($"Hello, {variable}!");
    }
}
Imports System

Friend Class Program
	Public Shared Sub Main(String ByVal () As args)
		Console.Write("Enter your name: ")
		Dim variable As String = Console.ReadLine()
		Console.WriteLine($"Hello, {variable}!")
	End Sub
End Class
VB   C#

在这里,程序会提示用户输入姓名,使用 Console.ReadLine 读取输入内容,然后在一行字符串上打印个性化的问候信息。

控制台颜色

您可以更改控制台文本的前景色和背景色,以增强视觉效果。为此可使用 Console.ForegroundColorConsole.BackgroundColor 属性。

using System;

class Program 
{
public static void Main()
    { 
        Console.ForegroundColor = ConsoleColor.Green;
        Console.BackgroundColor = ConsoleColor.DarkBlue;
        Console.WriteLine("Colored Console Output");
        // Reset colors to default
        Console.ResetColor();
    }
}
using System;

class Program 
{
public static void Main()
    { 
        Console.ForegroundColor = ConsoleColor.Green;
        Console.BackgroundColor = ConsoleColor.DarkBlue;
        Console.WriteLine("Colored Console Output");
        // Reset colors to default
        Console.ResetColor();
    }
}
Imports System

Friend Class Program
Public Shared Sub Main()
		Console.ForegroundColor = ConsoleColor.Green
		Console.BackgroundColor = ConsoleColor.DarkBlue
		Console.WriteLine("Colored Console Output")
		' Reset colors to default
		Console.ResetColor()
End Sub
End Class
VB   C#

此代码示例将前景色设置为绿色,背景色设置为深蓝色,然后在打印文本后将颜色重置为默认颜色。

高级控制台输出

对于更高级的情况,如打印格式化数据、表格或进度指示器,可以使用 NuGet 包管理器中的第三方库(如 ConsoleTables ),或使用高级格式化技术实施自定义解决方案。

using System;
using ConsoleTables;

class Program
{
    public static void Main()
    { 
        var table = new ConsoleTable("ID", "Name", "Age");
        table.AddRow(1, "John", 25);
        table.AddRow(2, "Alice", 30);
        Console.WriteLine(table);
    }
}
using System;
using ConsoleTables;

class Program
{
    public static void Main()
    { 
        var table = new ConsoleTable("ID", "Name", "Age");
        table.AddRow(1, "John", 25);
        table.AddRow(2, "Alice", 30);
        Console.WriteLine(table);
    }
}
Imports System
Imports ConsoleTables

Friend Class Program
	Public Shared Sub Main()
		Dim table = New ConsoleTable("ID", "Name", "Age")
		table.AddRow(1, "John", 25)
		table.AddRow(2, "Alice", 30)
		Console.WriteLine(table)
	End Sub
End Class
VB   C#

在本例中,"ConsoleTables "库用于将格式化的表格打印到控制台。这使控制台窗口输出看起来更现代、更整洁。

控制台窗口:使用 ConsoleTables 库将格式化的表格打印到控制台。

IronPrint:简化 .NET 打印功能

IronPrint IronPrint 是 Iron Software 开发的多功能打印库,旨在将强大的打印功能无缝集成到.NET 开发人员的应用程序中。无论您是开发网络应用程序、桌面应用程序还是移动解决方案,IronPrint 都能确保在各种 .NET 平台上提供无缝、可部署的打印体验。

IronPrint for .NET:C# 打印库

IronPrint 的主要功能

1.跨平台支持

IronPrint 兼容各种环境,确保您的应用程序可以在不同平台上利用其打印功能,包括

  • Windows (7+, Server 2016+)
  • MacOS (10+)
  • iOS (11+)
  • 安卓应用程序接口 21+ (v5 "棒棒糖")

支持 .NET 版本

该库支持多个 .NET 版本,因此适用于各种项目:

  • .NET 8、7、6、5 和 Core 3.1+ 版本
  • .NET 框架 (4.6.2+)

3.项目类型支持

IronPrint 支持 .NET 生态系统中的不同项目类型:

  • 移动 (Xamarin & MAUI & Avalonia)
  • 台式机 (WPF & MAUI & Windows Avalonia)

  • 控制台 (应用程序和图书馆)

4.广泛的格式支持

IronPrint 可处理一系列文档格式,包括 PDF、PNG、HTML、TIFF、GIF、JPEG、IMAGE 和 BITMAP。这种灵活性使其成为处理不同类型文档的开发人员的多功能选择。

5.自定义打印设置

利用 IronPrint 的自定义设置,定制您的打印体验。调整 Dpi、指定副本数量、设置纸张方向 (纵向或横向)等等。该库使开发人员能够对打印配置进行微调,以满足其应用程序的需求。

安装过程

开始使用 IronPrint 的过程非常简单。请按照以下步骤安装程序库:

1.使用 NuGet 软件包管理器安装 IronPrint 软件包:

    :ProductInstall

或者直接从官方的 IronPrint NuGet 网站 或从解决方案的 NuGet 软件包管理器。

![使用 NuGet 软件包管理器安装 IronPrint,方法是在 NuGet 软件包管理器的搜索栏中搜索 "ironprint",然后选择项目并点击安装按钮。](/static-assets/print/blog/csharp-print-cole/csharp-print-cole-4.webp)

2.安装完成后,在 C# 代码顶部加入以下语句即可开始使用 IronPrint:

    using IronPrint;
    using IronPrint;
Imports IronPrint
VB   C#
  1. 通过将许可证密钥值分配给 "License "类的 "LicenseKey "属性,应用有效的已购许可证或试用密钥:
    License.LicenseKey = "IRONPRINT.MYLICENSE.KEY.1EF01";
    License.LicenseKey = "IRONPRINT.MYLICENSE.KEY.1EF01";
License.LicenseKey = "IRONPRINT.MYLICENSE.KEY.1EF01"
VB   C#

代码示例

1.打印文档

使用 IronPrint 可以简化打印文档的过程。只需将文件路径传递给 打印 方法:

using IronPrint;

// Print the document
Printer.Print("newDoc.pdf");
using IronPrint;

// Print the document
Printer.Print("newDoc.pdf");
Imports IronPrint

' Print the document
Printer.Print("newDoc.pdf")
VB   C#

2.使用对话框打印

要在打印前显示打印对话框,请使用 显示打印对话框 方法:

using IronPrint;

// Show print dialog
Printer.ShowPrintDialog("newDoc.pdf");
using IronPrint;

// Show print dialog
Printer.ShowPrintDialog("newDoc.pdf");
Imports IronPrint

' Show print dialog
Printer.ShowPrintDialog("newDoc.pdf")
VB   C#

3.自定义打印设置

通过实例化 打印设置 类的代码:

using IronPrint;

// Configure print setting
PrintSettings printSettings = new PrintSettings();
printSettings.Dpi = 150;
printSettings.NumberOfCopies = 2;
printSettings.PaperOrientation = PaperOrientation.Portrait;

// Print the document with custom settings
Printer.Print("newDoc.pdf", printSettings);
using IronPrint;

// Configure print setting
PrintSettings printSettings = new PrintSettings();
printSettings.Dpi = 150;
printSettings.NumberOfCopies = 2;
printSettings.PaperOrientation = PaperOrientation.Portrait;

// Print the document with custom settings
Printer.Print("newDoc.pdf", printSettings);
Imports IronPrint

' Configure print setting
Private printSettings As New PrintSettings()
printSettings.Dpi = 150
printSettings.NumberOfCopies = 2
printSettings.PaperOrientation = PaperOrientation.Portrait

' Print the document with custom settings
Printer.Print("newDoc.pdf", printSettings)
VB   C#

许可与支持

虽然 IronPrint 是一个付费的程序库,但您可以通过以下方式获得许可 免费试用 许可证。使用 IronPrint 的 许可证页面.如需更多支持和咨询,请联系 Iron 软件团队.

结论

向控制台打印是 C# 开发人员的一项基本技能。无论是基本文本输出、格式化字符串、用户输入,还是高级控制台操作,了解各种可用的技术都能帮助您创建健壮且用户友好的控制台应用程序。请尝试使用这些方法,并根据具体项目的要求进行调整。

IronPrint IronPrint 是一款功能强大的 .NET 打印库,强调准确性、易用性和速度。如需了解有关 IronPrint 的更多信息,并探索 IronPrint 提供的全部功能和代码示例,请访问官方网站 文献资料API文档 page.

IronPrint 还提供 免费试用 以测试其在商业环境中的全部潜力。不过,您需要购买 许可证 试用期结束后。其精简版软件包的起价为 $749。从以下地址下载该库 这里 试一试!

< 前一页
C# 打印列表(开发人员的工作原理)
下一步 >
C# 打印语句(适用于开发者的工作原理)

准备开始了吗? 版本: 2024.8 刚刚发布

免费NuGet下载 总下载量: 7,289 查看许可证 >