.NET ヘルプ

デベロッパー向けC#のプリント文(その仕組み)

更新済み 3月 26, 2024
共有:

印刷はアプリケーション開発の基本であり、開発者はコンソールや物理的な文書を通じてユーザーとコミュニケーションをとることができる。 C#では、 印刷ステートメント この記事では、その使い方、オプション、ベストプラクティスを紹介する。

C#(シーシャープ)入門; 印刷ステートメント

print**文は、C#(シーシャープ)でコンソールに情報を出力するために使用します。 プログラムとユーザー間のコミュニケーションを容易にし、メッセージやデータ、操作の結果を表示する方法を提供する。 このステートメントは、デバッグ、ユーザーとの対話、プログラム実行中の一般的な情報出力に不可欠である。

基本構文

C#のprint文の基本構文では、Console.WriteLineメソッドを使用し、指定した文字列や値の後に自動的に改行を追加します。 System名前空間の中にあるConsoleクラスには、標準出力ストリームに情報を出力するためのWriteLineメソッドが組み込まれている。 このメソッドは、複数の変数を持つ文字列行と、標準入力ストリーム経由で取得したユーザー入力の両方で動作する。

以下は簡単な例です:

using System;
class Program
{
    public static void Main()
    {
        Console.WriteLine("Hello, C# Print Statement!");
    }
}
using System;
class Program
{
    public static void Main()
    {
        Console.WriteLine("Hello, C# Print Statement!");
    }
}
Imports System
Friend Class Program
	Public Shared Sub Main()
		Console.WriteLine("Hello, C# Print Statement!")
	End Sub
End Class
VB   C#

この単純な例では、Console クラスの WriteLine メソッドを使用して、指定された文字列をコンソールに出力し、その後に改行します。

変数と値の印刷

文字列リテラルや変数の数値を Console.WriteLine メソッドのパラメータとして含めると、それを表示できます。 例えば:

using System;
class Program
{
    public static void Main()
    {
        string message = "Welcome to C#";
        int number = 42;
        Console.WriteLine(message);
        Console.WriteLine("The answer is: " + number);
    }
}
using System;
class Program
{
    public static void Main()
    {
        string message = "Welcome to C#";
        int number = 42;
        Console.WriteLine(message);
        Console.WriteLine("The answer is: " + number);
    }
}
Imports System
Friend Class Program
	Public Shared Sub Main()
		Dim message As String = "Welcome to C#"
		Dim number As Integer = 42
		Console.WriteLine(message)
		Console.WriteLine("The answer is: " & number)
	End Sub
End Class
VB   C#

上記のコード例では、WriteLineメソッドを使って、message変数とnumber変数の値をコンソールに出力している。

C#シーシャープステートメント(開発者のための仕組み):図1 - Console.WriteLineの出力

特殊文字と文字列のフォーマット

C#(シーシャープ)には、プレースホルダや文字列補間を使用して出力をフォーマットするさまざまな方法があります。 次の例を確認してほしい:

using System;
class Program
{
    public static void Main()
    {
        string name = "John";
        int age = 30;
        Console.WriteLine("Name: {0}, Age: {1}", name, age);
        Console.WriteLine($"Name: {name}, Age: {age}");
    }
}
using System;
class Program
{
    public static void Main()
    {
        string name = "John";
        int age = 30;
        Console.WriteLine("Name: {0}, Age: {1}", name, age);
        Console.WriteLine($"Name: {name}, Age: {age}");
    }
}
Imports System
Friend Class Program
	Public Shared Sub Main()
		Dim name As String = "John"
		Dim age As Integer = 30
		Console.WriteLine("Name: {0}, Age: {1}", name, age)
		Console.WriteLine($"Name: {name}, Age: {age}")
	End Sub
End Class
VB   C#

どちらのアプローチも結果は同じで、フォーマットされた文字列に変数値を挿入することができる。

その他の書式オプション

ライン・ターミネーター

デフォルトでは、行末は"♪"です。 (復帰+改行). を使って変更できる:

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
VB   C#

書式のカスタマイズ

フォーマット文字列は、プレースホルダーやフォーマットオプションでカスタマイズできる。 例えば:

DateTime currentDate = DateTime.Now;
Console.WriteLine("Today is {0:D}", currentDate);
DateTime currentDate = DateTime.Now;
Console.WriteLine("Today is {0:D}", currentDate);
Dim currentDate As DateTime = DateTime.Now
Console.WriteLine("Today is {0:D}", currentDate)
VB   C#

複合書式設定

以下は、文字配列を複合フォーマットして1行に印刷する例である:

double price = 19.99;
char [] chars = { 'A', 'B', 'C' };
Console.WriteLine("Product: {0}, Price: ${1:F2} 
 Characters: {2}", "Widget", price, new string(chars));
double price = 19.99;
char [] chars = { 'A', 'B', 'C' };
Console.WriteLine("Product: {0}, Price: ${1:F2} 
 Characters: {2}", "Widget", price, new string(chars));
Dim price As Double = 19.99
Dim chars() As Char = { "A"c, "B"c, "C"c }
Console.WriteLine("Product: {0}, Price: ${1:F2} Characters: {2}", "Widget", price, New String(chars))
VB   C#

このコード例では、商品名と価格は複合フォーマットを使ってフォーマットされ、文字はnew stringを使って文字列として出力される。(文字).

改行と改段

改行や改段をコントロールすることは、出力を構造化する上で非常に重要だ。 Console.WriteLineメソッドは自動的に次の行を追加しますが、Console.Write**メソッドを使うこともできます。 唯一の違いは、次の例に示すように、このメソッドがコンソール・ウィンドウの同じ行に表示されることである:

using System;
class Program
{
    public static void Main()
    {
        Console.Write("This ");
        Console.Write("is ");
        Console.Write("on ");
        Console.WriteLine("the same line.");
    }
}
using System;
class Program
{
    public static void Main()
    {
        Console.Write("This ");
        Console.Write("is ");
        Console.Write("on ");
        Console.WriteLine("the same line.");
    }
}
Imports System
Friend Class Program
	Public Shared Sub Main()
		Console.Write("This ")
		Console.Write("is ")
		Console.Write("on ")
		Console.WriteLine("the same line.")
	End Sub
End Class
VB   C#

上記のコード例では、次のように出力される:「これは同じ行にあります。

アイアンプリント:.NET 用オールインワン印刷ライブラリ

IronPrint (アイアンプリント)ソフトウェア(アイアンソフトウェア)によって開発された、.NET開発者のために設計された、物理的なドキュメントを印刷するための包括的な印刷ライブラリです。 C#(シーシャープ)アプリケーションでドキュメントを印刷するための汎用的なソリューションです。 物理的なプリンターが利用できない場合、ドキュメントの印刷にはデフォルトのプリンターがデフォルト値として使用される。

C#プリントステートメント (開発者のための仕組み):図2 - IronPrint for .NET (.NET用アイアンプリント):C#印刷ライブラリ

インストール

IronPrint (アイアンプリント) を使用してインストールできます。 NuGet Package ManagerコンソールまたはVisual Studioパッケージマネージャを使用します。

NuGetパッケージマネージャーコンソールを使用してIronPrintをインストールするには、次のコマンドを使用します:

Install-Package IronPrint

あるいは、Visual Studioを使ってプロジェクトにインストールすることもできる。 ソリューションエクスプローラを右クリックし、ソリューションのNuGetパッケージマネージャの管理をクリックします。 NuGetのブラウズタブでアイアンプリントを検索し、インストールをクリックしてプロジェクトに追加します:

C# (シーシャープ) Printステートメント (開発者向けの仕組み):図3 - NuGetパッケージマネージャを使ってIronPrintをインストールするには、NuGetパッケージマネージャの検索バーで"ironprint"を検索し、プロジェクトを選択してインストールボタンをクリックします。

アイアンプリントを選ぶ理由

1.クロスプラットフォーム・マジック

Windowsでも、macOSでも、iOSでも、Androidでも、 IronPrint (アイアンプリント) が背中を押してくれる。 .NETバージョン8、7、6、5、Core 3.1+で動作するため、非常に汎用性が高い。

2.フォーマットの柔軟性

PDFからPNG、HTML、TIFF、GIF、JPEG、IMAGE、BITMAPまで、アイアンプリントはすべてを処理します。

3.印刷設定

DPI、部数、用紙の向きなど、印刷設定のカスタマイズが可能。

4.簡単な取り付け

IronPrint (アイアンプリント)のインストールは簡単です。NuGetパッケージマネージャーコンソールを使ってコマンドを入力するだけです: **と入力すればOKです。

どのように機能するのか?

**印刷 IronPrint(アイアンプリント)を使えば、公園を散歩するようなものです。 この簡単なコード例を見てください。 **ダイアログ コントロール 印刷設定:

using IronPrint;
// Print a document
Printer.Print("newDoc.pdf");
// Show a print dialog
Printer.ShowPrintDialog("newDoc.pdf");
// Customize print settings
PrintSettings printSettings = new PrintSettings();
printSettings.Dpi = 150;
printSettings.NumberOfCopies = 2;
printSettings.PaperOrientation = PaperOrientation.Portrait;
Printer.Print("newDoc.pdf", printSettings);
using IronPrint;
// Print a document
Printer.Print("newDoc.pdf");
// Show a print dialog
Printer.ShowPrintDialog("newDoc.pdf");
// Customize print settings
PrintSettings printSettings = new PrintSettings();
printSettings.Dpi = 150;
printSettings.NumberOfCopies = 2;
printSettings.PaperOrientation = PaperOrientation.Portrait;
Printer.Print("newDoc.pdf", printSettings);
Imports IronPrint
' Print a document
Printer.Print("newDoc.pdf")
' Show a print dialog
Printer.ShowPrintDialog("newDoc.pdf")
' Customize print settings
Dim printSettings As New PrintSettings()
printSettings.Dpi = 150
printSettings.NumberOfCopies = 2
printSettings.PaperOrientation = PaperOrientation.Portrait
Printer.Print("newDoc.pdf", printSettings)
VB   C#

アイアンプリント(IronPrint)とその印刷ハブとしての機能の詳細については、以下をご覧ください。 [ドキュメント](https://ironsoftware.com/csharp/print/docs/) ページ APIについてもっと詳しく知りたい方は、こちらをご覧ください。 [APIリファレンス**](https://ironsoftware.com/csharp/print/object-reference/api/) ページ

結論

C#(シーシャープ)のprint文は、ユーザーとのコミュニケーション、情報の表示、コードのデバッグのための強力なツールです。 初心者でも経験豊富な開発者でも、Console.WriteLineメソッドの効果的な使い方を理解することは、情報量が多くユーザーフレンドリーなアプリケーションを作成するために不可欠です。

IronPrint (アイアンプリント) 正確さ、使いやすさ、スピードを求めるのであれば、印刷ライブラリが最適です。 Webアプリケーションの構築、MAUI、Avalonia、.NET関連など、IronPrintはあなたをサポートします。

*IronPrint*は有償のライブラリですが、IronPrintは有償のライブラリです。 [無料体験**](licensing) ページ

開発者としての生活を少し楽にする準備はできているだろうか? IronPrint**を入手 (アイアンプリント) [以下の内容を日本語に翻訳します:

ここに

ご希望のイディオムや技術用語が追加されることによって、より適切な翻訳が提供できる場合もありますので、詳細なコンテキストを教えていただけると幸いです。](https://ironsoftware.com/csharp/print/)!

< 以前
C# コンソールに出力する(開発者向けの使い方)

準備はできましたか? バージョン: 2024.8 新発売

無料のNuGetダウンロード 総ダウンロード数: 7,144 View Licenses >