.NET 帮助

C# If(它如何为开发人员工作)

发布 2023年五月23日
分享:

在本教程中,我们将分析 ifelse 语句的概念,以及如何在 C# 程序中有效地使用它们。我们还将探讨布尔表达式和条件运算符等相关概念。那么,让我们直接进入!

了解 If 语句

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

if 语句检查给定的布尔表达式是否求值为 "true"。如果是,语句块内的代码 (大括号中的代码) 将被执行。如果布尔表达式的值为 "false",则跳过语句块内的代码。

If Else 语句的力量

现在,如果你想在 if 条件为假时执行其他代码怎么办?这就是可选的 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
VB   C#

在上述情况中,如果布尔表达式的值为 "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
VB   C#

在上述代码中,我们首先声明一个名为 "年龄 "的整数变量,并将其赋值为 21。然后,我们使用 if else 语句检查年龄是否大于或等于 18。如果条件为真,程序将打印 "您有资格投票!"到控制台。如果为假,则打印 "抱歉,您没有投票资格"。

使用布尔表达式

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

在上面的示例中,我们首先声明一个名为 "number "的整数变量,并将其赋值为 0,然后使用 if 语句检查数字是否大于 0。如果数值为假,我们将转到 else if 语句,检查数值是否小于 0。如果该条件为真,我们将打印 "数值为负"。最后,如果前面的条件都不满足,我们进入 else 块,打印 "数字为零"。

使用逻辑操作符组合条件

在某些情况下,您可能需要同时检查多个条件。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
VB   C#

在上述代码中,我们首先声明一个名为 age 的整数变量和一个名为 isStudent 的布尔变量。然后,我们使用带有逻辑运算符的 if else 语句来检查该人是否有资格享受折扣。如果年龄为 65 岁或以上,或者是 18 至 25 岁之间的学生,程序将打印 "您符合折扣条件!"否则,系统将打印 "对不起,您不符合折扣条件"。

使用 IronPDF 生成 PDF 文件 If Else 语句的相关应用

现在你已经牢固掌握了 C# if else 语句,让我们来探讨一下涉及到 IronPDF 图书馆

IronPDF 是一个功能强大的 .NET 库,可让您在 C# 应用程序中创建、编辑和提取 PDF 文件内容。

在本示例中,我们将创建一个简单的 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
VB   C#

在本代码示例中,我们使用 if else 语句根据客户所在地确定适当的税率。我们创建 从 HTML 字符串生成 PDF 发票.在 C# 中,我们可以利用 C#列表是一个功能强大的集合类,用于存储和操作一系列项目,如产品价格。

C# If(如何为开发人员工作) 图 1

结论

在本教程中,我们介绍了 C# if else 语句的基础知识,探讨了各种条件和逻辑运算符,并通过实际示例更好地理解了这一概念。我们甚至还演示了使用功能强大的 IronPDF 图书馆,它提供了 免费试用 和从 $749 开始的许可证。

请记住,在掌握编程概念时,练习至关重要。不断尝试不同的场景,运用新发现的 if else 语句知识和其他相关概念。

< 前一页
C# 多行字符串(对开发者的作用)
下一步 >
安装 NuGet Powershell(开发人员教程中的工作原理)

准备开始了吗? 版本: 2024.9 刚刚发布

免费NuGet下载 总下载量: 10,731,156 查看许可证 >