上一篇: Visual Studio IDE 简介

下一篇: C# 数据类型

C# 基本语法

引言

在学习C#编程时,熟悉基本语法是非常重要的。以下教程将介绍C#的一些基本语法规则和概念,帮助您开始编写C#代码。

程序结构

一个典型的C#程序包含以下几个部分:

  • 使用关键字 using引入命名空间
  • 定义一个类(Class)
  • 在类中定义一个或多个方法(Method)
  • Main方法中编写程序的执行逻辑

下面是一个简单的C# "Hello, World!" 程序:

                using System;

                namespace HelloWorldApp {
                    class Program {
                        static void Main(string[] args) {
                            Console.WriteLine("Hello, World!");
                        }
                    }
                }
                

变量与数据类型

C# 是一种强类型语言,变量在声明时必须指定其数据类型。以下是一些常用的数据类型:

  • 整数:int, long, short
  • 浮点数:float, double
  • 布尔值:bool
  • 字符:char
  • 字符串:string

变量声明示例:

                int age = 30;
                double salary = 50000.50;
                bool isEmployed = true;
                char initial = 'A';
                string name = "John Doe";
                

运算符与表达式

C#提供了一系列的运算符用于操作变量和常量。以下是一些常见的运算符类型:

  • 算术运算符:+,-,*,/,%
  • 比较运算符:<,>,<=,>=,==,!=
  • 逻辑运算符:&&(与),||(或),!(非)
  • 赋值运算符:=,+=,-=,*=,/=, %=

表达式示例:

                int x = 10;
                int y = 20;

                int sum = x + y;
                bool isGreater = x > y;
                bool isTrue = x < y && isGreater;
                x += 5; // x = x + 5;
                

流程控制结构

C#提供了条件判断和循环等流程控制结构来实现代码执行逻辑。

条件判断 - if、else if、else:

                int number = 10;

                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.");
                }
                

循环 - for、while、do-while:

for循环示例:

                for (int i = 0; i < 5; i++) {
                    Console.WriteLine($"Iteration {i}");
                }
                

while循环示例:

                int counter = 0;

                while (counter < 5) {
                    Console.WriteLine($"Counter: {counter}");
                    counter++;
                }
                
                do-while循环示例:
                
                int value = 10;

                do {
                    Console.WriteLine($"Value: {value}");
                    value -= 2;
                } while (value > 0);
                

注释

C#提供两种类型的注释:

  • 单行注释:用 // 表示
  • 多行注释:用 /**/ 表示

注释示例:

                // This is a single-line comment.

                /*
                This is a
                multi-line
                comment.
                */
                

通过掌握本教程介绍的基本语法,您已经迈出了学习C#编程的重要一步。在接下来的学习过程中,请多实践和尝试不同的代码示例,以加深对C#编程知识的理解。祝您学习愉快!