Przejdź do treści stopki
POMOC .NET

Funkcja PRINT w języku C#: przewodnik dla programistów

Printing in C# is a foundational skill for developers, enabling them to communicate with users and log crucial information. The Console class is a versatile tool that offers a range of methods to cater to different scenarios. Microsoft C# programming language also provides a Print method that can be used to print to paper.

In this comprehensive article, we'll explore various aspects of C# printing, covering basic techniques, variable printing, list printing, advanced features, and an in-depth exploration of the IronPrint library.

Basic Printing with Console.WriteLine

At the core of C# printing lies the Console.WriteLine method. It's the go-to function for displaying formatted output information on the console. The simplicity of this method is evident in the following example:

Console.WriteLine("Hello, C# Print Function!"); // Print a string and move to a new line
Console.WriteLine("Hello, C# Print Function!"); // Print a string and move to a new line
Console.WriteLine("Hello, C# Print Function!") ' Print a string and move to a new line
$vbLabelText   $csharpLabel

This single line prints the specified string line to the console, followed by a newline character, neatly presenting the output.

Printing Variables

Printing variable values is a common requirement. C# facilitates this through string interpolation or concatenation. Here's an example illustrating variable printing:

int age = 25;
Console.WriteLine($"Age: {age}"); // Interpolating the variable 'age' into the string
int age = 25;
Console.WriteLine($"Age: {age}"); // Interpolating the variable 'age' into the string
Dim age As Integer = 25
Console.WriteLine($"Age: {age}") ' Interpolating the variable 'age' into the string
$vbLabelText   $csharpLabel

In this instance, the value of the age variable is inserted into the string, providing a dynamic and informative output.

C# Print Function (How It Works For Developers): Figure 1 - Same Line Variable Output

Printing User Input

One common scenario involves printing user input to the console. Rozważmy następujący przykład:

Console.Write("Enter your name: ");
string name = Console.ReadLine(); // Read input from the user
Console.WriteLine($"Hello, {name}!"); // Print a personalized greeting
Console.Write("Enter your name: ");
string name = Console.ReadLine(); // Read input from the user
Console.WriteLine($"Hello, {name}!"); // Print a personalized greeting
Console.Write("Enter your name: ")
Dim name As String = Console.ReadLine() ' Read input from the user
Console.WriteLine($"Hello, {name}!") ' Print a personalized greeting
$vbLabelText   $csharpLabel

In this case, the program prompts the user for input, captures it, and then the WriteLine method prints a personalized greeting message.

Printing a List

Lists are prevalent in C# programming language, and printing their elements is a useful skill. The following code demonstrates how to print each element of a list on a new line:

List<string> fruits = new List<string> { "Apple", "Banana", "Orange" };
foreach (var fruit in fruits)
{
    Console.WriteLine(fruit); // Print each element on a new line
}
List<string> fruits = new List<string> { "Apple", "Banana", "Orange" };
foreach (var fruit in fruits)
{
    Console.WriteLine(fruit); // Print each element on a new line
}
Dim fruits As New List(Of String) From {"Apple", "Banana", "Orange"}
For Each fruit In fruits
	Console.WriteLine(fruit) ' Print each element on a new line
Next fruit
$vbLabelText   $csharpLabel

This loop iterates through the list and prints each fruit on a separate line.

Printing Enum Values

Enums are often used to represent a set of named constants. Printing enum values helps visualize and confirm their usage in your code:

enum Days { Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday }
Days today = Days.Wednesday;
Console.WriteLine($"Today is {today}"); // Print the current day
enum Days { Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday }
Days today = Days.Wednesday;
Console.WriteLine($"Today is {today}"); // Print the current day
Friend Enum Days
	Sunday
	Monday
	Tuesday
	Wednesday
	Thursday
	Friday
	Saturday
End Enum
Private today As Days = Days.Wednesday
Console.WriteLine($"Today is {today}") ' Print the current day
$vbLabelText   $csharpLabel

This provides clarity on the current state of selection represented by the enum.

C# Print Function (How It Works For Developers): Figure 2 - Enum Output

Printing to Console without Newline

If you want to print text content without introducing new lines between each output, the Console.Write method is your choice. This method prevents the output from moving to the next line.

using System;

class Program
{
    public static void Main(string[] args) 
    {
        // Each Write call adds text to the current line
        Console.Write("This ");
        Console.Write("will ");
        Console.Write("be ");
        Console.Write("on ");
        Console.Write("the ");
        Console.Write("same ");
        Console.Write("line.");
    }
}
using System;

class Program
{
    public static void Main(string[] args) 
    {
        // Each Write call adds text to the current line
        Console.Write("This ");
        Console.Write("will ");
        Console.Write("be ");
        Console.Write("on ");
        Console.Write("the ");
        Console.Write("same ");
        Console.Write("line.");
    }
}
Imports System

Friend Class Program
	Public Shared Sub Main(ByVal args() As String)
		' Each Write call adds text to the current line
		Console.Write("This ")
		Console.Write("will ")
		Console.Write("be ")
		Console.Write("on ")
		Console.Write("the ")
		Console.Write("same ")
		Console.Write("line.")
	End Sub
End Class
$vbLabelText   $csharpLabel

This sequence of Write calls produces output on the same line, maintaining a cohesive presentation. This is the only difference between the Write method and the WriteLine method.

Printing with Unicode Characters

Enhance your output with Unicode characters, adding flair to your console messages. Na przykład:

Console.WriteLine("Hello \u2665 C#"); // \u2665 represents a heart symbol
Console.WriteLine("Hello \u2665 C#"); // \u2665 represents a heart symbol
Console.WriteLine("Hello " & ChrW(&H2665).ToString() & " C#") ' \u2665 represents a heart symbol
$vbLabelText   $csharpLabel

Incorporating Unicode characters provides a visually appealing touch to your console output.

Debugging with Print Statements

During development, print statements are invaluable for debugging. By strategically placing Console.WriteLine statements in your code, you can output variable values or execution points to understand program flow and identify issues.

int x = 5;
int y = 10;
int sum = x + y;
Console.WriteLine($"The sum of {x} and {y} is {sum}"); // Print sum to debug
int x = 5;
int y = 10;
int sum = x + y;
Console.WriteLine($"The sum of {x} and {y} is {sum}"); // Print sum to debug
Dim x As Integer = 5
Dim y As Integer = 10
Dim sum As Integer = x + y
Console.WriteLine($"The sum of {x} and {y} is {sum}") ' Print sum to debug
$vbLabelText   $csharpLabel

This aids in tracking variable values and understanding how calculations or conditions are being processed.

C# Print Function (How It Works For Developers): Figure 3 - Debugging Output

Formatowanie złożone

Composite string formatting allows for more dynamic and complex output. You can embed placeholders in a string and replace them with values:

double price = 19.99;
Console.WriteLine("Product: {0}, Price: ${1:F2}", "Widget", price); // Use placeholders in string
double price = 19.99;
Console.WriteLine("Product: {0}, Price: ${1:F2}", "Widget", price); // Use placeholders in string
Dim price As Double = 19.99
Console.WriteLine("Product: {0}, Price: ${1:F2}", "Widget", price) ' Use placeholders in string
$vbLabelText   $csharpLabel

Here, the placeholders {0} and {1} are replaced by the corresponding values, offering a flexible way to structure your output.

Formatting Date and Time

Printing the current date and time is a frequent requirement. C# provides various formatting options to display date and time information:

DateTime currentDate = DateTime.Now;
Console.WriteLine($"Current Date: {currentDate:d}"); // Print date in short format
Console.WriteLine($"Current Time: {currentDate:t}"); // Print time in short format
DateTime currentDate = DateTime.Now;
Console.WriteLine($"Current Date: {currentDate:d}"); // Print date in short format
Console.WriteLine($"Current Time: {currentDate:t}"); // Print time in short format
Dim currentDate As DateTime = DateTime.Now
Console.WriteLine($"Current Date: {currentDate:d}") ' Print date in short format
Console.WriteLine($"Current Time: {currentDate:t}") ' Print time in short format
$vbLabelText   $csharpLabel

Customizing the format specifier (d, t, etc.) allows developers to present the information in different ways.

Handling Exceptions with Print

When an exception occurs, printing relevant information can aid in identifying the issue. Na przykład:

try 
{
    // Some code that may throw an exception
} 
catch (Exception ex) 
{
    Console.WriteLine($"Exception Caught: {ex.Message}"); // Print exception message
}
try 
{
    // Some code that may throw an exception
} 
catch (Exception ex) 
{
    Console.WriteLine($"Exception Caught: {ex.Message}"); // Print exception message
}
Try
	' Some code that may throw an exception
Catch ex As Exception
	Console.WriteLine($"Exception Caught: {ex.Message}") ' Print exception message
End Try
$vbLabelText   $csharpLabel

Printing the exception message assists in quickly diagnosing problems during runtime.

Advanced Printing with IronPrint: The C# Print Library

IronPrint, developed by Iron Software, is a robust and versatile printing library designed to empower .NET developers with seamless integration of printing capabilities into their applications. This comprehensive tool stands out for its compatibility across various platforms, including Windows, macOS, Android, and iOS, making it a go-to solution for developers working on diverse projects.

C# Print Function (How It Works For Developers): Figure 4 - IronPrint

One of IronPrint's key strengths lies in its broad file format support, accommodating PDF, PNG, HTML, TIFF, GIF, JPEG, and BMP. This flexibility allows developers to handle a wide array of printing requirements within their applications. Whether you are working on mobile, desktop, or console applications, IronPrint provides a unified solution for efficient and reliable printing.

IronPrint's feature set includes customizable print settings, enabling developers to tailor the printing experience to specific needs. Additionally, the library offers the option to display print dialogs, enhancing user interaction and control. The compatibility with different .NET versions and project types further contributes to its versatility, making it suitable for a variety of development scenarios.

Instalacja

To get started with IronPrint, install the package using NuGet:

nuget install IronPrint
nuget install IronPrint
SHELL

Podstawowe zastosowanie

Using IronPrint is straightforward. The following code prints a document using IronPrint:

using IronPrint;

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

Printer.Print("document.pdf"); // Print a document using IronPrint
Imports IronPrint

Printer.Print("document.pdf") ' Print a document using IronPrint
$vbLabelText   $csharpLabel

This minimal setup demonstrates the ease with which IronPrint integrates into your projects.

Print with Dialog

IronPrint extends functionality by allowing you to show a print dialog before printing:

Printer.ShowPrintDialog("document.pdf"); // Show a dialog before printing
Printer.ShowPrintDialog("document.pdf"); // Show a dialog before printing
Printer.ShowPrintDialog("document.pdf") ' Show a dialog before printing
$vbLabelText   $csharpLabel

This feature provides users with additional control over the printing process.

Customize Print Settings

IronPrint enables you to tailor print settings according to your requirements. The following example illustrates customizing settings such as DPI, number of copies, and paper orientation:

PrintSettings printSettings = new PrintSettings();
printSettings.Dpi = 150;
printSettings.NumberOfCopies = 2;
printSettings.PaperOrientation = PaperOrientation.Portrait;
Printer.Print("document.pdf", printSettings); // Customized print settings
PrintSettings printSettings = new PrintSettings();
printSettings.Dpi = 150;
printSettings.NumberOfCopies = 2;
printSettings.PaperOrientation = PaperOrientation.Portrait;
Printer.Print("document.pdf", printSettings); // Customized print settings
Dim printSettings As New PrintSettings()
printSettings.Dpi = 150
printSettings.NumberOfCopies = 2
printSettings.PaperOrientation = PaperOrientation.Portrait
Printer.Print("document.pdf", printSettings) ' Customized print settings
$vbLabelText   $csharpLabel

This flexibility empowers you to fine-tune the printing process based on specific needs. For more information on IronPrint and its capabilities, please visit this documentation page.

Obsługa wielu platform

IronPrint boasts compatibility with various environments, including Windows, macOS, Android, and iOS. It seamlessly integrates with .NET 8, 7, 6, 5, Core 3.1+, and .NET Framework (4.6.2+). Whether you're developing for the web, mobile, desktop, or console, IronPrint has you covered.

Wnioski

Mastering the art of printing in C# is essential for creating robust and user-friendly applications. Whether you're using the built-in capabilities of the Console class or leveraging advanced libraries like IronPrint, understanding these printing techniques is crucial. This comprehensive article has equipped you with the knowledge to print effectively in various scenarios, ensuring your applications communicate seamlessly with users and stakeholders.

While IronPrint is a paid library, free trial and its Lite package starts from $799. Download the library from here.

Często Zadawane Pytania

Jak mogę rozszerzyć możliwości drukowania w aplikacjach C#?

Aby rozszerzyć możliwości drukowania w aplikacjach C#, można skorzystać z biblioteki IronPrint. Obsługuje ona różne formaty plików, oferuje konfigurowalne ustawienia drukowania i jest kompatybilna z platformami takimi jak Windows, macOS, Android i iOS.

Jaka jest podstawowa metoda wyświetlania wyników na konsoli w języku C#?

Podstawową metodą wyświetlania wyników w konsoli w języku C# jest Console.WriteLine. Służy ona do wyświetlania sformatowanego tekstu i wartości w aplikacji konsolowej.

Jak mogę wydrukować elementy listy w języku C#?

Aby wydrukować elementy listy w języku C#, można użyć pętli foreach do iteracji przez listę i wyświetlenia każdego elementu za pomocą Console.WriteLine.

Czym jest formatowanie złożone w języku C#?

Formatowanie złożone w języku C# pozwala na użycie w ciągu znaków symboli zastępczych, które są zastępowane określonymi wartościami. Na przykład Console.WriteLine("Produkt: {0}, Cena: ${1:F2}", "Widget", cena) wykorzystuje symbole zastępcze do strukturyzowania wyniku.

Jak sformatować datę i godzinę w języku C#?

Język C# udostępnia specyfikatory formatu, takie jak „d” dla skróconej daty i „t” dla skróconego czasu. Można ich używać z funkcją DateTime.Now w celu wydrukowania sformatowanej daty i godziny.

Jak mogę drukować znaki Unicode w języku C#?

W języku C# można drukować znaki Unicode poprzez osadzenie w ciągu znaków sekwencji escape Unicode, takich jak \u2665 dla symbolu serca.

Jakie są typowe zastosowania Console.WriteLine w języku C#?

Funkcja Console.WriteLine w języku C# jest powszechnie używana do wyświetlania wartości zmiennych, debugowania, rejestrowania informacji oraz komunikacji z użytkownikami w aplikacjach konsolowych.

Jak zintegrować IronPrint z projektami w języku C#?

IronPrint można zintegrować z projektami C# poprzez zainstalowanie biblioteki IronPrint i wykorzystanie jej metod do zarządzania ustawieniami drukowania, obsługi okien dialogowych drukowania oraz obsługi różnych formatów plików na różnych platformach.

Jacob Mellor, Dyrektor Technologiczny @ Team Iron
Dyrektor ds. technologii

Jacob Mellor jest Chief Technology Officer w Iron Software i wizjonerskim inżynierem, pionierem technologii C# PDF. Jako pierwotny deweloper głównej bazy kodowej Iron Software, kształtuje architekturę produktów firmy od jej początku, przekształcając ją wspólnie z CEO Cameron Rimington w firmę liczą...

Czytaj więcej

Zespol wsparcia Iron

Jestesmy online 24 godziny, 5 dni w tygodniu.
Czat
Email
Zadzwon do mnie