.NET 幫助

C# 輸出到控制台(開發人員如何使用)

發佈 2024年4月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 語句輸出 "Hello World, Welcome to 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}nameage 的佔位符。這會生成格式化的輸出 "Name: John, Age: 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#

$ 符號表示字串插值,{} 中的表達式會評估為字串的一部分。{}**會被評估並插入字串。

控制台输出:名稱:Alice,年齡: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 是一個由 Iron Software 開發的多功能列印庫,旨在為 .NET 開發人員提供無縫整合強大列印功能到他們的應用程式中。無論您是在開發網頁應用程式、桌面應用程式還是行動解決方案,IronPrint 確保在各種 .NET 平台中提供無縫且可部署的列印體驗。

IronPrint for .NET:C# 列印庫

IronPrint的主要功能

1. 跨平台支持

IronPrint 兼容多種環境,確保您的應用程式可以在不同平台上利用其列印功能,包括:

  • Windows (7+,Server 2016+)
  • macOS (10+)

iOS (11+)

  • Android API 21+ (v5 "Lollipop")

2. .NET 版本支持

該庫支持多個 .NET 版本,使其適用於各種項目:

  • .NET 8, 7, 6, 5 和 Core 3.1+
  • .NET Framework (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)
  1. 安裝完成後,請在您的 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. 自訂列印設定

通過實例化程式來程式化配置列印設定 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);
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 Software 團隊.

結論

向控制台打印輸出是 C# 開發人員的一項基本技能。無論是基本的文本輸出、格式化字串、用戶輸入,還是高級的控制台操作,了解各種可用技術能讓你創建穩健且用戶友好的控制台應用程序。嘗試這些方法並根據你特定項目的需求進行調整。

IronPrint 作為一個強大的 .NET 列印庫,突顯了其精準性、易用性以及速度。如需了解更多有關 IronPrint 的資訊,並探索 IronPrint 所提供的所有功能和程式碼範例,請造訪官方網站。 文檔API 參考文獻 頁面。

IronPrint 還提供一個 免費試用 以測試其在商業環境中的全部潛力。然而,您需要購買一個 許可證 試用期結束後。其 Lite 套件起價為 $749。從以下位置下載庫 這裡 並試一試!

< 上一頁
C# 列印清單(適用於開發人員的工作方式)
下一個 >
C# 印出語句(開發人員如何使用)

準備開始了嗎? 版本: 2024.10 剛剛發布

免費 NuGet 下載 總下載次數: 9,531 查看許可證 >