.NET ヘルプ

C# 変数の印刷(開発者向けの仕組み)

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

C#(シーシャープ)で変数を印刷することは、開発者にとって必須のスキルです。 コードのデバッグ、ユーザーへの情報表示、あるいは単にプログラムの状態のチェックなど、Console.WriteLine文は標準出力ストリーム操作のための頼れるツールです。 名前空間 System の Console クラスは、変数値をコンソール・ウィンドウに表示するための Write および WriteLine メソッドを提供しています。

この包括的な記事では、さまざまなデータ型、書式設定オプション、高度なテクニックを取り上げながら、C#(シーシャープ)での変数の印刷のさまざまな側面を探ります。

基本的なバリアブル印刷

以下のコード例に示すように、Console.WriteLineメソッドを使えば簡単に数値を表示することができます。

int integerValue = 42; // specified value
Console.WriteLine($"Integer Value: {integerValue}"); // standard output stream
int integerValue = 42; // specified value
Console.WriteLine($"Integer Value: {integerValue}"); // standard output stream
Dim integerValue As Integer = 42 ' specified value
Console.WriteLine($"Integer Value: {integerValue}") ' standard output stream
VB   C#

この基本的な例では、整数変数を宣言します。 (integerValue) を実行し、Console.WriteLineステートメントを使用して、指定された値をコンソールに表示する。 文字列の前に$記号を付けると、文字列補間を利用して変数を文字列リテラルに直接埋め込むことができる。

文字列変数の印刷

string greeting = "Hello, C#!";
Console.WriteLine($"Greeting: {greeting}");
string greeting = "Hello, C#!";
Console.WriteLine($"Greeting: {greeting}");
Dim greeting As String = "Hello, C#!"
Console.WriteLine($"Greeting: {greeting}")
VB   C#

文字列変数の印刷も同じパターンである。 文字列変数を宣言する (ご挨拶)文字列の値を代入する(こんにちは、C#(シーシャープ)」。!")出力にはConsole.WriteLine**を使用する。 メッセージやテキスト情報を表示するのに便利です。

C# (シーシャープ) 変数印刷 (開発者向けの仕組み):図1 - 文字列変数の出力

変数の値を同じ行に表示するには、Console.Write メソッドを使用します。 両メソッドの唯一の違いは、WriteLineは最後に改行文字を残すので、次の出力は次の行に出力され、Writeメソッドは同じ行にすべてを出力することである。

1行に複数の変数

int x = 5, y = 10;
Console.WriteLine($"X: {x}, Y: {y}");
int x = 5, y = 10;
Console.WriteLine($"X: {x}, Y: {y}");
Dim x As Integer = 5, y As Integer = 10
Console.WriteLine($"X: {x}, Y: {y}")
VB   C#

文字列の中でカンマで区切れば、複数の変数を1行にまとめて表示できる。 これは、関連する情報を一緒に表示するのに有益である。

C# (シーシャープ) 変数印刷 (開発者向けの仕組み):図2 - 複数の変数を1行で出力する

変数の書式設定

double piValue = Math.PI;
Console.WriteLine($"Approximate Value of Pi: {piValue:F5}");
double piValue = Math.PI;
Console.WriteLine($"Approximate Value of Pi: {piValue:F5}");
Dim piValue As Double = Math.PI
Console.WriteLine($"Approximate Value of Pi: {piValue:F5}")
VB   C#

特に浮動小数点数の場合は、書式設定が重要になる。 ここでは、F5書式指定子によって、円周率の値が小数点以下5桁で表示される。

変数の連結

int apples = 3, oranges = 5;
Console.WriteLine("Total Fruits: " + (apples + oranges));
int apples = 3, oranges = 5;
Console.WriteLine("Total Fruits: " + (apples + oranges));
Dim apples As Integer = 3, oranges As Integer = 5
Console.WriteLine("Total Fruits: " & (apples + oranges))
VB   C#

文字列の連結は、より複雑な出力に使うことができる。 ここでは、果物の総数が計算され、同じ行に印字される。

バリアブルタイプの印刷

bool isTrue = true;
Console.WriteLine($"Is True? {isTrue}, Variable Type: {isTrue.GetType()}");
bool isTrue = true;
Console.WriteLine($"Is True? {isTrue}, Variable Type: {isTrue.GetType()}");
Dim isTrue As Boolean = True
Console.WriteLine($"Is True? {isTrue}, Variable Type: {isTrue.GetType()}")
VB   C#

変数のデフォルト値だけでなく、変数の型も表示することが有益な場合もある。 GetType()** メソッドでこれを達成する。

変数を印刷するための高度なテクニック

String.Format**の使用

int width = 10, height = 5;
string formattedOutput = String.Format("Dimensions: {0} x {1}", width, height); Console.WriteLine(formattedOutput);
int width = 10, height = 5;
string formattedOutput = String.Format("Dimensions: {0} x {1}", width, height); Console.WriteLine(formattedOutput);
Dim width As Integer = 10, height As Integer = 5
Dim formattedOutput As String = String.Format("Dimensions: {0} x {1}", width, height)
Console.WriteLine(formattedOutput)
VB   C#

String.Format**メソッドは、文字列をフォーマットして変数をプリントする別の方法を提供し、出力構造をより制御できるようにする。

バーベイタム文字列リテラル

string filePath = @"C:\MyDocuments\file.txt";
Console.WriteLine($"File Path: {filePath}");
string filePath = @"C:\MyDocuments\file.txt";
Console.WriteLine($"File Path: {filePath}");
Dim filePath As String = "C:\MyDocuments\file.txt"
Console.WriteLine($"File Path: {filePath}")
VB   C#

パスまたはエスケープ文字を含む文字列の場合、逐語的な文字列リテラル (の前に@を付ける) を使えば、コードを簡単にすることができる。 ここでは、文字列フォーマットがファイル・パスを簡単に表示するのに役立っている。

コンソール出力制御

コンソール出力のリダイレクト

次のコード例は、コンソール・ウィンドウの出力をファイルに書き出すのに役立つ:

using System;
using System.IO;
class Program
{
// public static void Main
    public static void Main(string [] args)
    {
        string outputPath = "output.txt";
        using (StreamWriter sw = new StreamWriter(outputPath))
        {
            Console.SetOut(sw);
            Console.WriteLine("This will be written to the file.");
        }
    }
}
using System;
using System.IO;
class Program
{
// public static void Main
    public static void Main(string [] args)
    {
        string outputPath = "output.txt";
        using (StreamWriter sw = new StreamWriter(outputPath))
        {
            Console.SetOut(sw);
            Console.WriteLine("This will be written to the file.");
        }
    }
}
Imports System
Imports System.IO
Friend Class Program
' public static void Main
	Public Shared Sub Main(ByVal args() As String)
		Dim outputPath As String = "output.txt"
		Using sw As New StreamWriter(outputPath)
			Console.SetOut(sw)
			Console.WriteLine("This will be written to the file.")
		End Using
	End Sub
End Class
VB   C#

コンソール出力をファイルにリダイレクトすることで、更なる分析やロギング目的で出力をキャプチャして保存することができます。

コンソールの色

Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("This text will be displayed in red.");
Console.ResetColor(); // Reset color to default
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("This text will be displayed in red.");
Console.ResetColor(); // Reset color to default
Console.ForegroundColor = ConsoleColor.Red
Console.WriteLine("This text will be displayed in red.")
Console.ResetColor() ' Reset color to default
VB   C#

コンソールの文字色を変更すると、特定の出力が視覚的に強調され、異なるタイプの情報を区別しやすくなります。

アイアンプリント:高度な印刷機能で.NET開発者に力を与える

IronPrint (アイアンプリント) はソフトウェア(アイアンソフトウェア)が開発した強力な印刷ライブラリです。 IronPrint (アイアンプリント)は.NETアプリケーションとシームレスに統合するために設計された包括的なプリントライブラリです。 IronPrint (アイアンプリント)は.NET開発者のための信頼できる機能豊富な印刷ライブラリです。 そのクロスプラットフォーム互換性、様々なドキュメントフォーマットのサポート、カスタマイズ可能な設定は、多様な印刷タスクを処理するための貴重なツールとなっている。 デスクトップ、モバイル、Webアプリケーションのいずれを開発する場合でも、IronPrint (アイアンプリント)は、.NET開発の日進月歩の中で印刷のニーズを満たす多用途のソリューションを提供します。

C# (シーシャープ) 変数印刷 (開発者のための仕組み):図3 - アイアンプリント

基本的な文書印刷からカスタマイズ可能な設定やクロスプラットフォーム互換性まで、開発者が多様な印刷要件に対応できるよう、さまざまな機能を提供する。

主な機能

  1. フォーマットサポート: IronPrintはPDF、PNG、HTML、TIFF、GIF、JPEG、BITMAPを含む様々なドキュメントフォーマットをサポートします。この多様性により、開発者はさまざまなタイプのコンテンツを印刷することができます。

  2. カスタマイズ可能な設定: 開発者は、アプリケーションの要件に応じて印刷設定を柔軟にカスタマイズできます。 これにはDPIを設定するオプションも含まれます。 (1インチ当たりのドット数)用紙の向きを指定する (縦向きまたは横向き)そして、部数をコントロールする。

  3. 印刷ダイアログ: IronPrintは、開発者が印刷前に印刷ダイアログを表示できるようにすることで、シームレスなユーザー体験を促進します。 これは、ユーザーが印刷プロセスと対話し、特定のオプションを選択する必要があるシナリオで有用である。

互換性とインストール

IronPrint (アイアンプリント)は様々な.NETバージョンとの幅広い互換性を誇り、幅広い開発者に利用可能です。 .NET 8、7、6、5、Core 3.1+、および.NETフレームワークをサポートしています。 (4.6.2+). このライブラリーは、モバイルを含む様々なプロジェクトに対応している。 (Xamarin、MAUI)デスクトップ (WPF、MAUI、ウィンドウズ・アヴァロニア)およびコンソールのアプリケーション。

インストール

IronPrintを使い始めるには、開発者はNuGet Package Managerを使ってライブラリを素早くインストールすることができる。

Install-Package IronPrint

また、このパッケージはアイアンプリント公式NuGetウェブサイト、またはソリューション用NuGetパッケージマネージャから直接ダウンロードすることもできます。

ライセンスキーの適用

アイアンプリントの機能を利用する前に、開発者は有効なライセンスまたはトライアルキーを適用する必要があります。 これには、ライセンス・キーを License クラスの LicenseKey プロパティに代入します。 次のコード・スニペットは、この手順を示している:

using IronPrint; 
// Apply license key
License.LicenseKey = "IRONPRINT.MYLICENSE.KEY.1EF01";
using IronPrint; 
// Apply license key
License.LicenseKey = "IRONPRINT.MYLICENSE.KEY.1EF01";
Imports IronPrint
' Apply license key
License.LicenseKey = "IRONPRINT.MYLICENSE.KEY.1EF01"
VB   C#

コード例

ドキュメントを印刷

以下の内容を日本語に翻訳してください:

To 印刷 IronPrintを使ってドキュメントを作成する場合、開発者は単純にファイルパスをPrintメソッドに渡すことができます:

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#

ダイアログを使用して印刷

を使用するシナリオの場合 **印刷ダイアログ が望ましい場合は、ShowPrintDialogメソッドを使用することができる:

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#

印刷設定のカスタマイズ

設定するには 印刷設定 プログラム上では、開発者は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#

コーディング例については、こちらをご覧ください。 コード例 ページ

結論

C#(シーシャープ)で変数を印刷することは、すべての開発者がマスターすべき基本的なスキルです。 Console.WriteLine**ステートメントは、文字列連結、文字列リテラル、文字列補間などの様々なフォーマット技術と組み合わせることで、変数値を出力する柔軟で効果的な方法を提供します。 さまざまなデータ型や高度な書式オプションなど、より複雑なシナリオに挑戦することで、C#(シーシャープ)プログラム内で効果的に情報を伝達する能力を高めることができます。

IronPrint (アイアンプリント)は有償のライブラリですが、開発者は以下の方法でその機能を試すことができます。 無料体験 ライセンスを取得した。 詳細については、開発者は公式サイトをご覧ください。 ドキュメント 以下のコンテンツを日本語に翻訳してください: APIリファレンス ページ ライブラリを以下からダウンロード [以下の内容を日本語に翻訳します:

ここに

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

< 以前
C# 印刷行(開発者向けの仕組み)
次へ >
C# 印刷機能(開発者向けの使い方)

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

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