跳至页脚内容
.NET 帮助

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

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

C# 打印语句简介

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

基本语法

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!");
    }
}
$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);
    }
}
$vbLabelText   $csharpLabel

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

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}");
    }
}
$vbLabelText   $csharpLabel

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

其他格式选项

线路终止器

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

Console.Out.NewLine = "\n";
// Set to newline character only
Console.Out.NewLine = "\n";
// 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);
    }
}
$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));
    }
}
$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.");
    }
}
$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# Print Statement (How It Works For Developers): Figure 3 - Install IronPrint using NuGet Package Manager by searching ironprint in the search bar of NuGet Package Manager, then selecting the project and clicking the Install button.

为什么选择 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);
    }
}
$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 拥有曼彻斯特大学土木工程一级荣誉工程学士学位(BEng)(1998-2001 年)。他的旗舰产品 IronPDF 和 Iron Suite for .NET 库在全球的 NuGet 安装量已超过 3000 万次,其基础代码继续为全球使用的开发人员工具提供动力。Jacob 拥有 25 年的商业经验和 41 年的编码专业知识,他一直专注于推动企业级 C#、Java 和 Python PDF 技术的创新,同时指导下一代技术领导者。

钢铁支援团队

我们每周 5 天,每天 24 小时在线。
聊天
电子邮件
打电话给我