跳至页脚内容
.NET 帮助

C# 打印语句:学习基础知识

打印是应用程序开发的一个基本方面,它允许开发人员通过控制台或物理文档与用户进行沟通。 在 C# 中, print 语句是一个用于显示信息的通用工具,在本文中,我们将探讨它的用法、选项和最佳实践。

C# 打印语句简介

在 C# 中, print语句用于将信息输出到控制台。 它促进了程序与用户之间的沟通,提供了一种显示消息、数据或操作结果的方式。 该语句对于调试、用户交互以及程序执行期间的一般信息输出至关重要。

基本语法

C# 中print语句的基本语法涉及使用Console.WriteLine方法,该方法会自动在指定的字符串或值后添加新行。 Console 类位于 System 命名空间中,它包含 WriteLine 方法,用于将信息输出到标准输出流。 该方法既可以处理包含多个变量的字符串行,也可以处理通过标准输入流获取的用户输入。

这是一个简单的例子:

using System;

class Program
{
    public static void Main()
    {
        // Print a greeting message to the console
        Console.WriteLine("Hello, C# Print Statement!");
    }
}
using System;

class Program
{
    public static void Main()
    {
        // Print a greeting message to the console
        Console.WriteLine("Hello, C# Print Statement!");
    }
}
Imports System

Friend Class Program
	Public Shared Sub Main()
		' Print a greeting message to the console
		Console.WriteLine("Hello, C# Print Statement!")
	End Sub
End Class
$vbLabelText   $csharpLabel

在这个简单的示例中, Console类的WriteLine方法用于将指定的字符串打印到控制台,并在后面添加一个新行。

打印变量和值

你可以通过将字符串字面量和变量的数值作为参数包含在Console.WriteLine方法中来打印它们。 例如:

using System;

class Program
{
    public static void Main()
    {
        // Define a string message and an integer number
        string message = "Welcome to C#";
        int number = 42;

        // Print the message and number to the console
        Console.WriteLine(message);
        Console.WriteLine("The answer is: " + number);
    }
}
using System;

class Program
{
    public static void Main()
    {
        // Define a string message and an integer number
        string message = "Welcome to C#";
        int number = 42;

        // Print the message and number to the console
        Console.WriteLine(message);
        Console.WriteLine("The answer is: " + number);
    }
}
Imports System

Friend Class Program
	Public Shared Sub Main()
		' Define a string message and an integer number
		Dim message As String = "Welcome to C#"
		Dim number As Integer = 42

		' Print the message and number to the console
		Console.WriteLine(message)
		Console.WriteLine("The answer is: " & number)
	End Sub
End Class
$vbLabelText   $csharpLabel

上面的代码示例展示了如何使用WriteLine方法将messagenumber变量的值打印到控制台。

C# 打印语句(开发者如何理解):图 1 - Console.WriteLine 输出

特殊字符和字符串格式化

C# 提供了多种使用占位符或字符串插值来格式化输出的方法。 请查看以下示例:

using System;

class Program
{
    public static void Main()
    {
        // Initialize variables
        string name = "John";
        int age = 30;

        // Use placeholders for string formatting
        Console.WriteLine("Name: {0}, Age: {1}", name, age);

        // Use string interpolation for a cleaner approach
        Console.WriteLine($"Name: {name}, Age: {age}");
    }
}
using System;

class Program
{
    public static void Main()
    {
        // Initialize variables
        string name = "John";
        int age = 30;

        // Use placeholders for string formatting
        Console.WriteLine("Name: {0}, Age: {1}", name, age);

        // Use string interpolation for a cleaner approach
        Console.WriteLine($"Name: {name}, Age: {age}");
    }
}
Imports System

Friend Class Program
	Public Shared Sub Main()
		' Initialize variables
		Dim name As String = "John"
		Dim age As Integer = 30

		' Use placeholders for string formatting
		Console.WriteLine("Name: {0}, Age: {1}", name, age)

		' Use string interpolation for a cleaner approach
		Console.WriteLine($"Name: {name}, Age: {age}")
	End Sub
End Class
$vbLabelText   $csharpLabel

两种方法都能达到相同的效果,即允许将变量值插入到格式化字符串中。

其他格式选项

线路终止器

默认情况下,行终止符为"\r\n"(回车符 + 换行符)。 您可以使用以下方法更改它:

Console.Out.NewLine = "\n";
// Set to newline character only
Console.Out.NewLine = "\n";
// Set to newline character only
Imports Microsoft.VisualBasic

Console.Out.NewLine = vbLf
' Set to newline character only
$vbLabelText   $csharpLabel

自定义格式

格式字符串允许使用占位符和格式选项进行自定义。 例如:

using System;

class Program
{
    public static void Main()
    {
        // Get the current date
        DateTime currentDate = DateTime.Now;

        // Print the current date in a long date pattern
        Console.WriteLine("Today is {0:D}", currentDate);
    }
}
using System;

class Program
{
    public static void Main()
    {
        // Get the current date
        DateTime currentDate = DateTime.Now;

        // Print the current date in a long date pattern
        Console.WriteLine("Today is {0:D}", currentDate);
    }
}
Imports System

Friend Class Program
	Public Shared Sub Main()
		' Get the current date
		Dim currentDate As DateTime = DateTime.Now

		' Print the current date in a long date pattern
		Console.WriteLine("Today is {0:D}", currentDate)
	End Sub
End Class
$vbLabelText   $csharpLabel

复合格式

以下是一个复合格式化并将字符数组打印在一行上的示例:

using System;

class Program
{
    public static void Main()
    {
        // Define a price and character array
        double price = 19.99;
        char[] chars = { 'A', 'B', 'C' };

        // Format the output string using placeholders
        Console.WriteLine("Product: {0}, Price: ${1:F2} | Characters: {2}", 
                          "Widget", price, new string(chars));
    }
}
using System;

class Program
{
    public static void Main()
    {
        // Define a price and character array
        double price = 19.99;
        char[] chars = { 'A', 'B', 'C' };

        // Format the output string using placeholders
        Console.WriteLine("Product: {0}, Price: ${1:F2} | Characters: {2}", 
                          "Widget", price, new string(chars));
    }
}
Imports System

Friend Class Program
	Public Shared Sub Main()
		' Define a price and character array
		Dim price As Double = 19.99
		Dim chars() As Char = { "A"c, "B"c, "C"c }

		' Format the output string using placeholders
		Console.WriteLine("Product: {0}, Price: ${1:F2} | Characters: {2}", "Widget", price, New String(chars))
	End Sub
End Class
$vbLabelText   $csharpLabel

在这个代码示例中,产品名称和价格使用复合格式进行格式化,字符使用new string(chars)作为字符串打印。

新行和换行符

控制新行和换行对于构建输出至关重要。 Console.WriteLine方法会自动添加新行,但您可以使用Console.Write方法在同一行上打印,如下例所示:

using System;

class Program
{
    public static void Main()
    {
        // Print parts of a sentence on the same line
        Console.Write("This ");
        Console.Write("is ");
        Console.Write("on ");
        Console.WriteLine("the same line.");
    }
}
using System;

class Program
{
    public static void Main()
    {
        // Print parts of a sentence on the same line
        Console.Write("This ");
        Console.Write("is ");
        Console.Write("on ");
        Console.WriteLine("the same line.");
    }
}
Imports System

Friend Class Program
	Public Shared Sub Main()
		' Print parts of a sentence on the same line
		Console.Write("This ")
		Console.Write("is ")
		Console.Write("on ")
		Console.WriteLine("the same line.")
	End Sub
End Class
$vbLabelText   $csharpLabel

上面的代码示例会产生如下打印输出:"这是同一行。 "

IronPrint:您的 .NET 一体化打印库

IronPrint由 Iron Software 开发,是一个全面的打印库,专为 .NET 开发人员设计,用于打印物理文档。 它提供了广泛的功能并支持各种环境,使其成为 C# 应用程序中打印文档的多功能解决方案。 如果物理打印机不可用,则使用默认打印机作为默认值来打印文档。

C# 打印语句(开发人员的工作原理):图 2 - IronPrint for .NET:C# 打印库

安装

IronPrint可以通过NuGet程序包管理器控制台或 Visual Studio 程序包管理器进行安装。

要使用 NuGet 程序包管理器控制台安装 IronPrint,请使用以下命令:

Install-Package IronPrint

或者,您可以使用 Visual Studio 将其安装到您的项目中。 右键单击"解决方案资源管理器",然后单击"管理解决方案的 NuGet 程序包管理器"。 在 NuGet 浏览选项卡中,搜索IronPrint ,然后单击"安装"将其添加到您的项目中:

! C# 打印语句(开发人员的工作方式):图 3 - 使用 NuGet 包管理器安装 IronPrint,方法是在 NuGet 包管理器的搜索栏中搜索"IronPrint",然后选择项目并单击"安装"按钮。

为什么选择 IronPrint?

1. 跨平台魔法

无论您使用的是 Windows、macOS、iOS 还是 Android 系统, IronPrint都能为您提供支持。 它与 .NET 版本 8、7、6、5 和 Core 3.1+ 兼容性良好,使其用途非常广泛。

2. 格式灵活性

从 PDF 到 PNG、HTML、TIFF、GIF、JPEG、IMAGE 和 BITMAP – IronPrint 都能处理。

3. 打印设置

允许自定义打印设置,包括 DPI、份数、纸张方向等。

4. 安装简便

安装 IronPrint 非常简单。只需使用 NuGet 包管理器控制台并输入命令: Install-Package IronPrint ,即可完成安装。

它是如何运作的?

使用 IronPrint 进行印刷简直易如反掌。 请看这个简单的代码示例,您可以轻松地通过dialog进行打印并控制打印设置

using IronPrint;

class PrintExample
{
    public static void Main()
    {
        // Print a document
        Printer.Print("newDoc.pdf");

        // Show a print dialog for user interaction
        Printer.ShowPrintDialog("newDoc.pdf");

        // Customize print settings
        PrintSettings printSettings = new PrintSettings
        {
            Dpi = 150,
            NumberOfCopies = 2,
            PaperOrientation = PaperOrientation.Portrait
        };

        // Print using the customized settings
        Printer.Print("newDoc.pdf", printSettings);
    }
}
using IronPrint;

class PrintExample
{
    public static void Main()
    {
        // Print a document
        Printer.Print("newDoc.pdf");

        // Show a print dialog for user interaction
        Printer.ShowPrintDialog("newDoc.pdf");

        // Customize print settings
        PrintSettings printSettings = new PrintSettings
        {
            Dpi = 150,
            NumberOfCopies = 2,
            PaperOrientation = PaperOrientation.Portrait
        };

        // Print using the customized settings
        Printer.Print("newDoc.pdf", printSettings);
    }
}
Imports IronPrint

Friend Class PrintExample
	Public Shared Sub Main()
		' Print a document
		Printer.Print("newDoc.pdf")

		' Show a print dialog for user interaction
		Printer.ShowPrintDialog("newDoc.pdf")

		' Customize print settings
		Dim printSettings As New PrintSettings With {
			.Dpi = 150,
			.NumberOfCopies = 2,
			.PaperOrientation = PaperOrientation.Portrait
		}

		' Print using the customized settings
		Printer.Print("newDoc.pdf", printSettings)
	End Sub
End Class
$vbLabelText   $csharpLabel

有关IronPrint及其作为打印中心的功能的更多详细信息,请访问文档页面

结论

C# 中的print语句是一个强大的工具,可用于与用户沟通、显示信息和调试代码。 无论你是新手还是经验丰富的开发者,了解如何有效地使用Console.WriteLine方法对于创建信息丰富且用户友好的应用程序都至关重要。

如果您想要精准、易用和快速的打印库, IronPrint是您的理想之选。 无论您是在构建 Web 应用程序、使用 MAUI、Avalonia 还是任何与 .NET 相关的项目, IronPrint都能为您提供支持。

IronPrint是一个付费图书馆,但提供免费试用

想让你的开发者生活更轻松一些吗? 从这里获取IronPrint

常见问题解答

C# 中打印语句的目的是什么?

在 C# 中,打印语句主要使用 Console.WriteLine,用于在控制台上显示信息。它在调试、用户交互及向用户显示数据或消息方面发挥着重要作用。

如何使用 Console.WriteLine 在 C# 中打印字符串和变量?

可以通过将字符串和变量作为参数传递给 Console.WriteLine 来打印。例如,Console.WriteLine("The value is " + variable); 将打印与变量值连接的字符串。

C# 中有哪些格式化输出的选项?

C# 提供了多种格式化选项,包括使用 $"" 语法的字符串插值和带有占位符的复合格式化,例如 Console.WriteLine("The total is {0}", total);

如何使用 Console.WriteLine 打印特殊字符?

可以在 C# 中使用转义序列打印特殊字符,例如字符串中的 \n 表示换行或 \t 表示制表符,传递给 Console.WriteLine

什么是 IronPrint,它如何为 .NET 开发人员带来好处?

IronPrint 是为 .NET 开发人员设计的全面打印库,用于简化物理文档的打印。它支持跨平台环境和多种文件格式,增强了易用性和跨 .NET 版本的兼容性。

如何在项目中安装 IronPrint?

可以使用 NuGet 包管理器安装 IronPrint,使其易于集成到 .NET 项目中,以增强打印功能。

IronPrint 支持哪些打印环境?

IronPrint 支持包括 Windows、macOS、iOS 和 Android 在内的多个环境,并与 .NET 版本 8、7、6、5 和 Core 3.1+ 兼容。

如何在 .NET 应用程序中使用 IronPrint 自定义打印设置?

IronPrint 允许通过 PrintSettings 类自定义打印设置,例如 DPI、打印份数和纸张方向,从而灵活控制打印过程。

IronPrint 有试用版吗?

是的,IronPrint 提供了一个免费试用版,开发人员可以利用它探索其功能和项目中的集成能力。

Jacob Mellor,Team Iron 的首席技术官
首席技术官

Jacob Mellor 是 Iron Software 的首席技术官,是 C# PDF 技术的先锋工程师。作为 Iron Software 核心代码库的原始开发者,自公司成立以来,他就塑造了公司的产品架构,并与首席执行官 Cameron Rimington 一起将其转变成一家公司,拥有50多人,服务于 NASA、特斯拉和全球政府机构。

Jacob 拥有曼彻斯特大学 (1998-2001) 的一级荣誉土木工程学士学位。1999 年在伦敦创办了自己的第一家软件公司,并于 2005 年创建了他的第一个 .NET 组件后,他专注于解决微软生态系统中的复杂问题。

他的旗舰 IronPDF 和 Iron Suite .NET 库在全球已获得超过 3000 万次的 NuGet 安装,其基础代码继续为全球使用的开发者工具提供支持。拥有 25 年商业经验和 41 年编程经验的 Jacob 仍专注于推动企业级 C#、Java 和 Python PDF 技术的创新,同时指导下一代技术领导者。