C#(基本语法)
数据类型
C#是一种强类型语言,变量必须声明类型。基本数据类型包括整型(int、long)、浮点型(float、double)、布尔型(bool)、字符型(char)和字符串型(string)。引用类型包括类、接口、数组等。
int age = 25;
double price = 19.99;
bool isActive = true;
char grade = 'A';
string name = "John";
变量与常量
变量用于存储数据,使用前需声明类型。常量使用const
关键字定义,初始化后不可更改。
int counter = 10;
const double PI = 3.14159;
运算符
C#支持算术运算符(+、-、*、/)、比较运算符(==、!=、>、<)、逻辑运算符(&&、||、!)和赋值运算符(=、+=、-=)。
int sum = 10 + 5;
bool isEqual = (sum == 15);
bool result = (true && false);
控制流语句
条件语句包括if-else
和switch
,循环语句包括for
、while
和do-while
。
if (age >= 18)
{Console.WriteLine("Adult");
}for (int i = 0; i < 5; i++)
{Console.WriteLine(i);
}while (counter > 0)
{counter--;
}
方法
方法是包含一系列语句的代码块,通过return
返回值(无返回值用void
)。参数可传递值或引用(ref
、out
)。
int Add(int a, int b)
{return a + b;
}void PrintMessage(string message)
{Console.WriteLine(message);
}
类和对象
类是面向对象的基础,包含字段、属性、方法和构造函数。对象是类的实例。
class Person
{public string Name { get; set; }public int Age { get; set; }public Person(string name, int age) {Name = name;Age = age;}public void Introduce() {Console.WriteLine($"Name: {Name}, Age: {Age}");}
}Person person = new Person("Alice", 30);
person.Introduce();
异常处理
使用try-catch-finally
块处理运行时错误,确保程序健壮性。
try
{int result = 10 / int.Parse("0");
}
catch (DivideByZeroException ex)
{Console.WriteLine("Cannot divide by zero.");
}
finally
{Console.WriteLine("Cleanup code here.");
}
集合类型
常见集合包括数组(Array)、列表(List)、字典(Dictionary)等,用于管理数据组。
int[] numbers = { 1, 2, 3 };
List<string> names = new List<string> { "Alice", "Bob" };
Dictionary<int, string> employees = new Dictionary<int, string>();
命名空间
命名空间用于组织代码,避免命名冲突。通过using
指令引入。
using System;
namespace MyApp
{class Program { ... }
}