如何有效使用 C# 打印行
在 C# 中打印行是控制台应用程序的一个基本方面,它涉及在控制台屏幕上显示文本或指定的值。 在 C# 控制台应用程序中,无论是处理标准输出流还是格式化字符串,了解如何高效地打印行都至关重要。
在本文中,我们将探讨与 C# 中打印行相关的各种方法和技巧。
印刷线基础知识
在 C# 中,打印一行通常需要使用Console.WriteLine方法。 我们先来看一个简单的例子:
using System;
class Program
{
public static void Main()
{
Console.WriteLine("Hello, C# Print Line!");
}
}Imports System
Friend Class Program
Public Shared Sub Main()
Console.WriteLine("Hello, C# Print Line!")
End Sub
End ClassImports System
Friend Class Program
Public Shared Sub Main()
Console.WriteLine("Hello, C# Print Line!")
End Sub
End Class在上面的代码中, Console.WriteLine语句输出指定的字符串值("Hello, C# Print Line!"),并在其后添加一个换行符。这是通过WriteLine方法实现的,该方法会在输出末尾添加一个换行符。
线路终止符
行终止符是表示行结束的特殊字符或序列。最常见的两个行终止符是回车符( '\r' )和换行符( '\n' )。 在 C# 中, Console.WriteLine方法会根据操作系统自动使用相应的当前行终止符。
public static void Main()
{
Console.WriteLine("This is on the first line.");
Console.WriteLine("This is on the second line.");
}public static void Main()
{
Console.WriteLine("This is on the first line.");
Console.WriteLine("This is on the second line.");
}Public Shared Sub Main()
Console.WriteLine("This is on the first line.")
Console.WriteLine("This is on the second line.")
End SubPublic Shared Sub Main()
Console.WriteLine("This is on the first line.")
Console.WriteLine("This is on the second line.")
End Sub在上面的示例中,程序执行后,每个Console.WriteLine都会在 C# 控制台窗口中生成一个新行,从而产生指定的两行。

指定线路终端
如果需要显式控制换行符,可以使用Console.Write方法并手动添加所需的换行符:
public static void Main()
{
Console.Write("This is on the first line.");
Console.Write('\r'); // Carriage return
Console.Write("This is on the same line but very far left position.");
}public static void Main()
{
Console.Write("This is on the first line.");
Console.Write('\r'); // Carriage return
Console.Write("This is on the same line but very far left position.");
}Imports Microsoft.VisualBasic
Public Shared Sub Main()
Console.Write("This is on the first line.")
Console.Write(ControlChars.Cr) ' Carriage return
Console.Write("This is on the same line but very far left position.")
End SubImports Microsoft.VisualBasic
Public Shared Sub Main()
Console.Write("This is on the first line.")
Console.Write(ControlChars.Cr) ' Carriage return
Console.Write("This is on the same line but very far left position.")
End Sub在这个例子中,回车符( '\r' )用于将光标定位到行首,导致文本的第二部分出现在最左侧的位置,即覆盖先前的输出。

打印多行
要打印多行而不重复使用Console.WriteLine语句,可以使用可变长度的参数列表:
public static void Main()
{
PrintLines("Line 1", "Line 2", "Line 3");
}
static void PrintLines(params string[] lines)
{
foreach (var line in lines)
{
Console.WriteLine(line);
}
}public static void Main()
{
PrintLines("Line 1", "Line 2", "Line 3");
}
static void PrintLines(params string[] lines)
{
foreach (var line in lines)
{
Console.WriteLine(line);
}
}Public Shared Sub Main()
PrintLines("Line 1", "Line 2", "Line 3")
End Sub
Shared Sub PrintLines(ParamArray ByVal lines() As String)
For Each line In lines
Console.WriteLine(line)
Next line
End SubPublic Shared Sub Main()
PrintLines("Line 1", "Line 2", "Line 3")
End Sub
Shared Sub PrintLines(ParamArray ByVal lines() As String)
For Each line In lines
Console.WriteLine(line)
Next line
End Sub我们创建的PrintLines方法接受一个指定的字符串参数数组,允许您传递任意数量的换行符来打印指定的字符串值:

格式化输出
格式化输出至关重要,尤其是在处理不同数据类型时。Console.WriteLine 方法提供了多个重载,它们接受指定的对象和格式信息:
public static void Main()
{
int answer = 42;
string name = "John Doe";
Console.WriteLine("The answer is {0}.", answer);
Console.WriteLine("Hello, {0}!", name);
}public static void Main()
{
int answer = 42;
string name = "John Doe";
Console.WriteLine("The answer is {0}.", answer);
Console.WriteLine("Hello, {0}!", name);
}Public Shared Sub Main()
Dim answer As Integer = 42
Dim name As String = "John Doe"
Console.WriteLine("The answer is {0}.", answer)
Console.WriteLine("Hello, {0}!", name)
End SubPublic Shared Sub Main()
Dim answer As Integer = 42
Dim name As String = "John Doe"
Console.WriteLine("The answer is {0}.", answer)
Console.WriteLine("Hello, {0}!", name)
End Sub在这个例子中, {0}是指定对象的占位符(在本例中是answer和name ),允许您在输出中包含可变数据并打印指定的格式信息。

换行符和Unicode字符
对于特殊换行符或 Unicode 字符,可以使用转义序列。 您还可以使用 Console.WriteLine 打印任何 ASCII 字面值或有效的 HTML 代码。例如,要在同一字符串中添加一个单行换行符:
public static void Main()
{
Console.WriteLine("This is line 1.\nThis is line 2.");
Console.WriteLine("Line 1\u000Aline 2");
}public static void Main()
{
Console.WriteLine("This is line 1.\nThis is line 2.");
Console.WriteLine("Line 1\u000Aline 2");
}Imports Microsoft.VisualBasic
Public Shared Sub Main()
Console.WriteLine("This is line 1." & vbLf & "This is line 2.")
Console.WriteLine("Line 1" & vbLf & "line 2")
End SubImports Microsoft.VisualBasic
Public Shared Sub Main()
Console.WriteLine("This is line 1." & vbLf & "This is line 2.")
Console.WriteLine("Line 1" & vbLf & "line 2")
End Sub这里, \n和\u000A(指定的 Unicode 字符)都表示换行符,导致文本在每种情况下都移到下一行。

随机布尔值
以下代码在Console.WriteLine方法中使用了字符串插值。 字符串插值是 C# 6.0 中引入的一项功能,它简化了在字符串字面量中嵌入表达式或变量并在控制台应用程序中正确显示指定的布尔值的过程。
using System;
class Program
{
static void Main()
{
Random rnd = new Random();
for (int i = 1; i <= 5; i++)
{
bool isTrue = rnd.Next(0, 2) == 1;
Console.WriteLine($"True or False: {isTrue}");
}
}
}using System;
class Program
{
static void Main()
{
Random rnd = new Random();
for (int i = 1; i <= 5; i++)
{
bool isTrue = rnd.Next(0, 2) == 1;
Console.WriteLine($"True or False: {isTrue}");
}
}
}Imports System
Friend Class Program
Shared Sub Main()
Dim rnd As New Random()
For i As Integer = 1 To 5
Dim isTrue As Boolean = rnd.Next(0, 2) = 1
Console.WriteLine($"True or False: {isTrue}")
Next i
End Sub
End ClassImports System
Friend Class Program
Shared Sub Main()
Dim rnd As New Random()
For i As Integer = 1 To 5
Dim isTrue As Boolean = rnd.Next(0, 2) = 1
Console.WriteLine($"True or False: {isTrue}")
Next i
End Sub
End Class表达式返回的指定数据将打印在控制台应用程序中,如下所示:

打印不同的数字格式
在编程中,打印各种数字格式是一个常见的需求,尤其是在处理双精度浮点数和单精度浮点数时。 同样,可以使用Console.WriteLine语句来精确、轻松地打印它们。
双精度浮点数
double doubleValue = 0.123456789;
Console.WriteLine($"Double Precision: {doubleValue:F7}");double doubleValue = 0.123456789;
Console.WriteLine($"Double Precision: {doubleValue:F7}");Dim doubleValue As Double = 0.123456789
Console.WriteLine($"Double Precision: {doubleValue:F7}")Dim doubleValue As Double = 0.123456789
Console.WriteLine($"Double Precision: {doubleValue:F7}")在这个例子中, F7指定双精度值应格式化为小数点后 7 位。 您可以调整"F"后面的数字来控制精度。
现有字符串
string existingString = "Hello, C#!";
Console.WriteLine($"Existing String: {existingString}");string existingString = "Hello, C#!";
Console.WriteLine($"Existing String: {existingString}");Dim existingString As String = "Hello, C#!"
Console.WriteLine($"Existing String: {existingString}")Dim existingString As String = "Hello, C#!"
Console.WriteLine($"Existing String: {existingString}")打印已存在的字符串很简单。 只需使用Console.WriteLine并包含要显示的字符串即可。
单精度浮点数
float singleValue = 0.123456789f;
Console.WriteLine($"Single Precision: {singleValue:F7}");float singleValue = 0.123456789f;
Console.WriteLine($"Single Precision: {singleValue:F7}");Dim singleValue As Single = 0.123456789F
Console.WriteLine($"Single Precision: {singleValue:F7}")Dim singleValue As Single = 0.123456789F
Console.WriteLine($"Single Precision: {singleValue:F7}")与双精度类似, F7格式说明符在这里用于单精度浮点数。 您可以根据精度要求调整"F"后面的数字。
Unlocking Powerful Printing Capabilities with IronPrint in C#
打印文档是许多应用程序的基本功能,而要充分发挥 C# 中的打印潜力,IronPrint 凭借其多功能性和丰富的功能脱颖而出。
IronPrint简介
IronPrint由 Iron Software 开发,是一个专为 .NET 生态系统(包括 C#)设计的高级打印库。 无论您是在开发桌面应用程序、移动应用程序还是 Web 应用程序,IronPrint 都能与您的 C# 项目无缝集成,提供一套全面的工具来处理各种打印需求。

IronPrint 的主要特点
1. 跨平台兼容性:
IronPrint 支持多种操作系统,包括 Windows、macOS、Android 和 iOS。 这种跨平台兼容性确保您的打印解决方案能够覆盖不同环境下的用户。
2. .NET版本支持:
IronPrint 兼容 .NET Framework 4.6.2 及以上版本、.NET Core 3.1+ 以及最新的 .NET 版本,覆盖范围广泛。
3. 项目类型支持:
IronPrint 可满足不同项目类型的需求,包括移动端(Xamarin 和 MAUI)、桌面端(WPF 和 MAUI)以及控制台端(应用程序和库)。 这种灵活性使其适用于各种应用架构。
4. 简单安装:
IronPrint 入门非常简单。 可以使用NuGet包管理器控制台并执行 Install-Package IronPrint 命令快速安装库。
IronPrint 的基本用法
以下是一个简单的示例,演示了在 C# 控制台应用程序中使用 IronPrint打印文档是多么容易:
using IronPrint;
class Program
{
static void Main()
{
Console.WriteLine("Printing Started...");
// Silent printing of a document
Printer.Print("document.pdf");
// Or display a print dialog
Printer.ShowPrintDialog("document.pdf");
Console.WriteLine("Printing Completed...");
}
}using IronPrint;
class Program
{
static void Main()
{
Console.WriteLine("Printing Started...");
// Silent printing of a document
Printer.Print("document.pdf");
// Or display a print dialog
Printer.ShowPrintDialog("document.pdf");
Console.WriteLine("Printing Completed...");
}
}Imports IronPrint
Friend Class Program
Shared Sub Main()
Console.WriteLine("Printing Started...")
' Silent printing of a document
Printer.Print("document.pdf")
' Or display a print dialog
Printer.ShowPrintDialog("document.pdf")
Console.WriteLine("Printing Completed...")
End Sub
End ClassImports IronPrint
Friend Class Program
Shared Sub Main()
Console.WriteLine("Printing Started...")
' Silent printing of a document
Printer.Print("document.pdf")
' Or display a print dialog
Printer.ShowPrintDialog("document.pdf")
Console.WriteLine("Printing Completed...")
End Sub
End Class此处的输出显示了使用Print和ShowPrintDialog方法打印文档的过程。 如果未安装物理打印机,则使用默认打印机进行打印。

先进的打印功能
IronPrint 不仅限于基本的打印任务,还提供以下高级功能:
- 静默打印:使用Printer.PrintAsync打印文档而不显示对话框。
- 自定义打印设置:使用PrintSettings类微调打印参数。
- 异步打印:异步执行打印操作,以防止阻塞主线程。
- 选择打印机: GetPrinterNames方法允许您从可用打印机中进行选择,从而对打印过程进行更精细的控制。
平台特定调整
IronPrint 允许您针对不同的平台定制打印解决方案。 例如,在使用面向特定平台(如 Windows、Android、iOS 或 macOS)的 .NET Core 项目时,您可以相应地调整项目文件中的TargetFrameworks属性。
要了解有关 IronPrint 的更多详细信息,请访问此文档和API 参考页面。
结论
在 C# 中打印行是控制台应用程序开发的基础技能。 无论你是显示文本、格式化输出还是控制行终止符,了解各种可用的技术都将增强你创建有效且易读的控制台程序的能力。 探索Console类提供的各种方法,尝试不同的格式化选项,并利用 C# 的灵活性,在应用程序中生成清晰且结构良好的控制台输出。
IronPrint 成为 C# 开发人员寻求强大而灵活的打印功能的有力助手。 IronPrint 具有跨平台支持、与各种 .NET 版本兼容以及高级打印功能,简化了在各种 C# 应用程序中实现打印解决方案的过程。 无论您是为桌面、移动设备还是 Web 开发,IronPrint 都能提供您所需的工具,将您的打印需求在 C# 开发世界中变为现实。
Jacob Mellor 是 Iron Software 的首席技术官,也是一位开创 C# PDF 技术的有远见的工程师。作为 Iron Software 核心代码库的原始开发者,他从公司成立之初就开始塑造公司的产品架构,与首席执行官 Cameron Rimington 一起将公司转变为一家拥有 50 多名员工的公司,为 NASA、特斯拉和全球政府机构提供服务。