ライブ環境でテストする
ウォーターマークなしで本番環境でテストしてください。
必要な場所でいつでも動作します。
このチュートリアルでは、C#プログラムで if
と else
文を効果的に使用するための概念を分解して解説します。 関連する概念として、ブール式や条件演算子についても探っていきます。 それでは、早速始めましょう。!
「if」文はプログラミングにおける基本的な概念です。 コード内で特定の条件に基づいて判断を行うために使用されます。 C#におけるif文の基本構文は次のとおりです
if (Boolean expression)
{
// Statements to execute if the Boolean expression is true
}
if (Boolean expression)
{
// Statements to execute if the Boolean expression is true
}
If Boolean expression Then
' Statements to execute if the Boolean expression is true
End If
if文は、指定されたブール式がtrue
で評価されるかどうかを確認します。 それが起こる場合、文ブロック内のコード (波括弧で囲まれたコード) 実行されます。 ブール式が false
と評価された場合、ステートメントブロック内のコードはスキップされます。
では、if条件がfalseの場合に他のコードを実行したい場合はどうしますか? そこでオプションのelseステートメントが登場します。 C#のif-else
ステートメントの構文は次のようになります
if (Boolean expression)
{
// Statements to execute if the Boolean expression is true
}
else
{
// Statements to execute if the Boolean expression is false
}
if (Boolean expression)
{
// Statements to execute if the Boolean expression is true
}
else
{
// Statements to execute if the Boolean expression is false
}
If Boolean expression Then
' Statements to execute if the Boolean expression is true
Else
' Statements to execute if the Boolean expression is false
End If
上記の場合、ブール式が true
に評価されると、if ブロック内のコードが実行されます。 それがfalse
と評価された場合、elseブロックのコードが代わりに実行されます。
C# の if else ステートメントの実際の使用例を見てみましょう。 プログラムを作成して、ある人が投票する資格があるかどうかを確認することを想像してください。 ほとんどの国では、投票年齢は18歳です。
以下の例は、if else 文を使用して投票資格を判定する方法を示します:
using System;
class Program
{
static void Main(string [] args)
{
int age = 21;
if (age >= 18)
{
Console.WriteLine("You are eligible to vote!");
}
else
{
Console.WriteLine("Sorry, you are not eligible to vote.");
}
}
}
using System;
class Program
{
static void Main(string [] args)
{
int age = 21;
if (age >= 18)
{
Console.WriteLine("You are eligible to vote!");
}
else
{
Console.WriteLine("Sorry, you are not eligible to vote.");
}
}
}
Imports System
Friend Class Program
Shared Sub Main(ByVal args() As String)
Dim age As Integer = 21
If age >= 18 Then
Console.WriteLine("You are eligible to vote!")
Else
Console.WriteLine("Sorry, you are not eligible to vote.")
End If
End Sub
End Class
上記のコードでは、最初に age
という名前の整数変数を宣言し、21という値を代入します。次に、if else文を使用して年齢が18以上かどうかを確認します。条件が真であれば、プログラムは「You are eligible to vote」と出力します。!コンソールに出力します。 それが false の場合は、「申し訳ありませんが、投票資格がありません。」と表示されます。
C#では、より複雑な条件を作成するためにさまざまな種類のブール式を使用できます。 一般的に使用される条件演算子には、以下のものがあります:
==
: 等価<
:より小さい>
: より大きい<=
:以下>=
:以上
例を見てみましょう。 もし、数値が正の数、負の数、またはゼロであるかどうかをチェックするプログラムを書きたい場合。 以下のコードスニペットは、if文と条件演算子を使用してこれを達成します:
using System;
class Program
{
static void Main(string [] args)
{
int number = 0;
if (number > 0)
{
Console.WriteLine("The number is positive.");
}
else if (number < 0)
{
Console.WriteLine("The number is negative.");
}
else
{
Console.WriteLine("The number is zero.");
}
}
}
using System;
class Program
{
static void Main(string [] args)
{
int number = 0;
if (number > 0)
{
Console.WriteLine("The number is positive.");
}
else if (number < 0)
{
Console.WriteLine("The number is negative.");
}
else
{
Console.WriteLine("The number is zero.");
}
}
}
Imports System
Friend Class Program
Shared Sub Main(ByVal args() As String)
Dim number As Integer = 0
If number > 0 Then
Console.WriteLine("The number is positive.")
ElseIf number < 0 Then
Console.WriteLine("The number is negative.")
Else
Console.WriteLine("The number is zero.")
End If
End Sub
End Class
上の例では、まず整数変数number
を宣言し、その値に0を割り当てます。次に、if文を使用してnumber
が0より大きいかどうかを確認します。条件が真の場合、「The number is positive.」を出力します。条件が偽の場合、次にelse if
文に移り、number
が0より小さいかどうかを確認します。この条件が真であれば、「The number is negative.」を出力します。最後に、これまでの条件がすべて満たされない場合、elseブロックに到達し、「The number is zero.」を出力します。
場合によっては、複数の条件を同時に確認する必要があるかもしれません。 C#はこれを実現するための論理演算子を提供します。 最も一般的に使用される論理演算子は
&&
: 論理 ANDもちろんです。続けてください。翻訳を希望する内容を入力してください。
**:論理 OR
もちろんです。続けてください。翻訳を希望する内容を入力してください。!`**:論理NOT
論理演算子をif文と共に使用する例を見てみましょう。 特定のストアで特別割引を受ける資格があるかどうかを判定するプログラムを作成すると仮定します。 シニアの方々向けには割引がご利用いただけます。 (65歳以上) 学生または (18歳から25歳までの年齢). 以下は、C#のif else文と論理演算子を使用して割引適格性を判断する方法を示すコードスニペットです。
using System;
class Program
{
static void Main(string [] args)
{
int age = 23;
bool isStudent = true;
if ((age >= 65)
(isStudent && (age >= 18 && age <= 25)))
{
Console.WriteLine("You are eligible for the discount!");
}
else
{
Console.WriteLine("Sorry, you are not eligible for the discount.");
}
}
}
using System;
class Program
{
static void Main(string [] args)
{
int age = 23;
bool isStudent = true;
if ((age >= 65)
(isStudent && (age >= 18 && age <= 25)))
{
Console.WriteLine("You are eligible for the discount!");
}
else
{
Console.WriteLine("Sorry, you are not eligible for the discount.");
}
}
}
Imports System
Friend Class Program
Shared Sub Main(ByVal args() As String)
Dim age As Integer = 23
Dim isStudent As Boolean = True
If (age >= 65)(isStudent AndAlso (age >= 18 AndAlso age <= 25)) Then
Console.WriteLine("You are eligible for the discount!")
Else
Console.WriteLine("Sorry, you are not eligible for the discount.")
End If
End Sub
End Class
上記のコードでは、まずage
という名前の整数変数とisStudent
という名前のブール変数を宣言します。 次に、論理演算子を使用したif else文を使って、その人物が割引の対象となるかどうかを確認します。 年齢が65歳以上の場合、または18歳から25歳の学生である場合、プログラムは「割引の対象です」と表示します。!他の場合、「申し訳ありませんが、割引の対象外です。」と表示されます。
ここまでで C# の if else ステートメントについてしっかりと理解できたので、それを実際に応用してみましょう。 IronPDF ライブラリ。
IronPDFは、C#アプリケーション内でPDFファイルを作成、編集、内容を抽出することができる強力な.NETライブラリです。
この例では、顧客の所在地に基づいて異なる税率を適用するシンプルなPDF請求書ジェネレーターを作成します。 このシナリオでは、if else 文を活用する絶好の機会が提供されます。
まず、次のコマンドを実行してNuGetを介してIronPDFをインストールします:
Install-Package IronPdf
次に、異なる地域の顧客に対して異なる税率で請求書を生成する簡単なプログラムを作成しましょう。
using System;
using IronPdf;
class Program
{
static void Main(string [] args)
{
string customerLocation = "Europe";
double taxRate;
if (customerLocation == "USA")
{
taxRate = 0.07;
}
else if (customerLocation == "Europe")
{
taxRate = 0.20;
}
else
{
taxRate = 0.15;
}
double productPrice = 100.0;
double totalTax = productPrice * taxRate;
double totalPrice = productPrice + totalTax;
string invoiceContent = $@"
<h1>Invoice</h1>
<p>Product Price: ${productPrice}</p>
<p>Tax Rate: {taxRate * 100}%</p>
<p>Total Tax: ${totalTax}</p>
<p>Total Price: ${totalPrice}</p>
";
var pdf = new ChromePdfRenderer();
var document = pdf.RenderHtmlAsPdf(invoiceContent);
document.SaveAs("Invoice.pdf");
}
}
using System;
using IronPdf;
class Program
{
static void Main(string [] args)
{
string customerLocation = "Europe";
double taxRate;
if (customerLocation == "USA")
{
taxRate = 0.07;
}
else if (customerLocation == "Europe")
{
taxRate = 0.20;
}
else
{
taxRate = 0.15;
}
double productPrice = 100.0;
double totalTax = productPrice * taxRate;
double totalPrice = productPrice + totalTax;
string invoiceContent = $@"
<h1>Invoice</h1>
<p>Product Price: ${productPrice}</p>
<p>Tax Rate: {taxRate * 100}%</p>
<p>Total Tax: ${totalTax}</p>
<p>Total Price: ${totalPrice}</p>
";
var pdf = new ChromePdfRenderer();
var document = pdf.RenderHtmlAsPdf(invoiceContent);
document.SaveAs("Invoice.pdf");
}
}
Imports System
Imports IronPdf
Friend Class Program
Shared Sub Main(ByVal args() As String)
Dim customerLocation As String = "Europe"
Dim taxRate As Double
If customerLocation = "USA" Then
taxRate = 0.07
ElseIf customerLocation = "Europe" Then
taxRate = 0.20
Else
taxRate = 0.15
End If
Dim productPrice As Double = 100.0
Dim totalTax As Double = productPrice * taxRate
Dim totalPrice As Double = productPrice + totalTax
Dim invoiceContent As String = $"
<h1>Invoice</h1>
<p>Product Price: ${productPrice}</p>
<p>Tax Rate: {taxRate * 100}%</p>
<p>Total Tax: ${totalTax}</p>
<p>Total Price: ${totalPrice}</p>
"
Dim pdf = New ChromePdfRenderer()
Dim document = pdf.RenderHtmlAsPdf(invoiceContent)
document.SaveAs("Invoice.pdf")
End Sub
End Class
このコード例では、顧客の所在地に基づいた適切な税率を決定するために、if else文を使用します。 私たちは作成します HTML文字列からのPDF請求書. C#では、私たちは C# リスト製品価格のような一連の項目を保存および操作するための強力なコレクションクラスです。
このチュートリアル全体を通じて、C# の if else 文の基本をカバーし、さまざまな条件および論理演算子を探求し、概念をよりよく理解するための実際の例を検討しました。 強力なIronPDFを使用した実用的なアプリケーションのデモンストレーションも行いました IronPDF ライブラリ、これは提供しています 無料試用 およびライセンスは $749 から開始します。
覚えておいてください、プログラミングの概念を習得するには、練習が重要です。異なるシナリオで実験を続けて、if else文やその他の関連する概念に関する新しい知識を適用していきましょう。
9つの .NET API製品 オフィス文書用