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 { ... }
}
相关推荐
Ray Liang5 小时前
用六边形架构与整洁架构对比是伪命题?
java·python·c#·架构设计
Scout-leaf3 天前
WPF新手村教程(三)—— 路由事件
c#·wpf
用户298698530143 天前
程序员效率工具:Spire.Doc如何助你一键搞定Word表格排版
后端·c#·.net
mudtools4 天前
搭建一套.net下能落地的飞书考勤系统
后端·c#·.net
玩泥巴的5 天前
搭建一套.net下能落地的飞书考勤系统
c#·.net·二次开发·飞书
唐宋元明清21885 天前
.NET 本地Db数据库-技术方案选型
windows·c#
lindexi5 天前
dotnet DirectX 通过可等待交换链降低输入渲染延迟
c#·directx·d2d·direct2d·vortice
qq_454245035 天前
基于组件与行为的树状节点系统
数据结构·c#
bugcome_com5 天前
C# 类的基础与进阶概念详解
c#
雪人不是菜鸡5 天前
简单工厂模式
开发语言·算法·c#