- C# 简介
C# 是由微软开发的面向对象的编程语言
运行在.NET框架上,具有强大的类型安全和内存管理
广泛用于Windows应用程序、Web开发、游戏开发(Unity)等
- 基本语法结构
csharp
using System; // 引入命名空间
namespace HelloWorld // 命名空间声明
{
class Program // 类声明
{
static void Main(string[] args) // 主方法,程序入口点
{
Console.WriteLine("Hello, World!"); // 输出语句
}
}
}
3. 基本数据类型
类型 描述 示例
int 整数 int age = 25;
double 双精度浮点数 double price = 19.99;
float 单精度浮点数 float temperature = 36.6f;
decimal 高精度小数 decimal salary = 5000.50m;
bool 布尔值 bool isActive = true;
char 单个字符 char grade = 'A';
string 字符串 string name = "John";
4. 变量和常量
csharp
// 变量声明和赋值
int number = 10;
string message = "Hello";
// 常量声明
const double PI = 3.14159;
5. 运算符
csharp
// 算术运算符
int result = 10 + 5; // +, -, *, /, %
// 比较运算符
bool isEqual = (10 == 5); // ==, !=, >, <, >=, <=
// 逻辑运算符
bool condition = (true && false); // && (AND), || (OR), ! (NOT)
6. 控制流程
条件语句
csharp
// if-else
if (age >= 18)
{
Console.WriteLine("成年人");
}
else
{
Console.WriteLine("未成年人");
}
// switch
switch (day)
{
case 1:
Console.WriteLine("星期一");
break;
default:
Console.WriteLine("其他天");
break;
}
循环语句
csharp
// for循环
for (int i = 0; i < 10; i++)
{
Console.WriteLine(i);
}
// while循环
while (condition)
{
// 循环体
}
// foreach循环(用于集合)
foreach (var item in collection)
{
Console.WriteLine(item);
}
7. 数组和集合
csharp
// 数组
int[] numbers = new int[5] {1, 2, 3, 4, 5};
// 列表(动态数组)
List
names.Add("Alice");
names.Add("Bob");
// 字典
Dictionary<string, int> ages = new Dictionary<string, int>();
ages["Alice"] = 25;
8. 方法(函数)
csharp
// 方法定义
public int Add(int a, int b)
{
return a + b;
}
// 方法调用
int sum = Add(5, 3);
9. 类和对象
csharp
// 类定义
public class Person
{
// 字段
public string Name;
private int age;
// 属性
public int Age
{get { return age; }set { age = value; }
}// 方法
public void Introduce()
{Console.WriteLine($"我叫{Name},今年{Age}岁");
}
}
// 创建对象
Person person = new Person();
person.Name = "张三";
person.Age = 25;
person.Introduce();
10. 异常处理
csharp
try
{
// 可能抛出异常的代码
int result = 10 / int.Parse("0");
}
catch (DivideByZeroException ex)
{
Console.WriteLine("除以零错误: " + ex.Message);
}
catch (Exception ex)
{
Console.WriteLine("发生错误: " + ex.Message);
}
finally
{
// 无论是否发生异常都会执行的代码
Console.WriteLine("执行完成");
}