C#(基本语法)

数据类型

C#是一种强类型语言,变量必须声明类型。基本数据类型包括整型(int、long)、浮点型(float、double)、布尔型(bool)、字符型(char)和字符串型(string)。引用类型包括类、接口、数组等。

csharp 复制代码
int age = 25;
double price = 19.99;
bool isActive = true;
char grade = 'A';
string name = "John";

变量与常量

变量用于存储数据,使用前需声明类型。常量使用const关键字定义,初始化后不可更改。

csharp 复制代码
int counter = 10;
const double PI = 3.14159;

运算符

C#支持算术运算符(+、-、*、/)、比较运算符(==、!=、>、<)、逻辑运算符(&&、||、!)和赋值运算符(=、+=、-=)。

csharp 复制代码
int sum = 10 + 5;
bool isEqual = (sum == 15);
bool result = (true && false);

控制流语句

条件语句包括if-elseswitch,循环语句包括forwhiledo-while

csharp 复制代码
if (age >= 18) 
{
    Console.WriteLine("Adult");
}

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

while (counter > 0) 
{
    counter--;
}

方法

方法是包含一系列语句的代码块,通过return返回值(无返回值用void)。参数可传递值或引用(refout)。

csharp 复制代码
int Add(int a, int b) 
{
    return a + b;
}

void PrintMessage(string message) 
{
    Console.WriteLine(message);
}

类和对象

类是面向对象的基础,包含字段、属性、方法和构造函数。对象是类的实例。

csharp 复制代码
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块处理运行时错误,确保程序健壮性。

csharp 复制代码
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)等,用于管理数据组。

csharp 复制代码
int[] numbers = { 1, 2, 3 };
List<string> names = new List<string> { "Alice", "Bob" };
Dictionary<int, string> employees = new Dictionary<int, string>();

命名空间

命名空间用于组织代码,避免命名冲突。通过using指令引入。

csharp 复制代码
using System;
namespace MyApp 
{
    class Program { ... }
}
相关推荐
SAJalon1 小时前
C#数组全面解析
c#
henreash2 小时前
xLua和C#交互
开发语言·c#·交互
★YUI★14 小时前
学习游戏制作记录(克隆技能)7.25
学习·游戏·unity·c#
坚持吧202115 小时前
【无标题】word 中的中文排序
开发语言·c#
_oP_i15 小时前
c# openxml 打开加密 的word读取内容
开发语言·c#·word
醉酒的李白、16 小时前
C#观察者模式示例代码
观察者模式·c#
咩咩觉主1 天前
Unity编辑器拓展 IMGUI与部分Utility知识总结(代码+思维导图)
unity·c#·编辑器·游戏引擎
无规则ai1 天前
C#入门实战:数字计算与条件判断
c#·visual studio
bianguanyue2 天前
WPF——自定义ListBox
c#·wpf