C# 中的 if...else 语句函数

首页 / C#入门教程 / C# 中的 if...else 语句函数

if语句后面可以跟随可选的else语句,该语句在布尔表达式为false时执行。

if...else - 语法

C#中if.else语句的语法是-

if(boolean_expression) {
   /* 如果布尔表达式为真,则将执行语句 */
} else {
   /* 如果布尔表达式为假,语句将执行 */
}

if...else - 流程图

C# if...else statement
using System;

namespace DecisionMaking {
   class Program {
      static void Main(string[] args) {
         /* 局部变量定义 */
         int a = 100;
         
         /* 检查布尔条件 */
         if (a < 20) {
            /* 如果条件为真,则打印以下内容 */
            Console.WriteLine("a is less than 20");
         } else {
            /* 如果条件为假,则打印以下内容 */
            Console.WriteLine("a is not less than 20");
         }
         Console.WriteLine("value of a is : {0}", a);
         Console.ReadLine();
      }
   }
}

编译并执行上述代码时,将生成以下输出-

无涯教程网

a is not less than 20;
value of a is : 100

if...elseif...else 语句

If语句后面可以跟随可选的Else If.Else语句,这对于使用单个If.Else If语句测试各种条件非常有用。

链接:https://www.learnfk.comhttps://www.learnfk.com/csharp/if-else-statement-in-csharp.html

来源:LearnFk无涯教程网

C#中if.else语句的语法是-

if(boolean_expression 1) {
   /* 当布尔表达式 1 为真时执行 */
} 
else if( boolean_expression 2) {
   /* 当布尔表达式 2 为真时执行 */
} 
else if( boolean_expression 3) {
   /* 当布尔表达式 3 为真时执行 */
} else {
   /* 当上述条件都不为真时执行 */
}
using System;

namespace DecisionMaking {
   class Program {
      static void Main(string[] args) {
         /* 局部变量定义 */
         int a = 100;
         
         /* 检查布尔条件 */
         if (a == 10) {
            /* 如果条件为真,则打印以下内容 */
            Console.WriteLine("Value of a is 10");
         } 
         else if (a == 20) {
            /* if else if 条件为真 */
            Console.WriteLine("Value of a is 20");
         } 
         else if (a == 30) {
            /* if else if 条件为真 */
            Console.WriteLine("Value of a is 30");
         } else {
            /* 如果没有一个条件为真 */
            Console.WriteLine("None of the values is matching");
         }
         Console.WriteLine("Exact value of a is: {0}", a);
         Console.ReadLine();
      }
   }
}

编译并执行上述代码时,将生成以下输出-

无涯教程网

None of the values is matching
Exact value of a is: 100

祝学习愉快!(内容编辑有误?请选中要编辑内容 -> 右键 -> 修改 -> 提交!)

技术教程推荐

邱岳的产品手记 -〔邱岳〕

设计模式之美 -〔王争〕

Django快速开发实战 -〔吕召刚〕

分布式金融架构课 -〔任杰〕

流程型组织15讲 -〔蒋伟良〕

如何讲好一堂课 -〔薛雨〕

零基础实战机器学习 -〔黄佳〕

B端体验设计入门课 -〔林远宏(汤圆)〕

程序员职业规划手册 -〔雪梅〕

好记忆不如烂笔头。留下您的足迹吧 :)