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 { ... }
}
相关推荐
刘欣的博客9 小时前
C# CS架构程序发版升级的走数据库方案
c#·单文件升级自己的方式
Yorlen_Zhang11 小时前
Python Tkinter Text 控件完全指南:从基础编辑器到富文本应用
开发语言·python·c#
不绝19111 小时前
C#进阶:预处理指令/反射,Gettype,Typeof/关键类
开发语言·c#
大鹏说大话11 小时前
告别 MSBuild 脚本混乱:用 C# 和 Nuke 构建清晰、可维护的现代化构建系统
开发语言·c#
czhc114007566312 小时前
通信 28
c#
bugcome_com16 小时前
C# 程序结构详解:从 Hello World 开始
c#
唐梓航-求职中17 小时前
编程-技术-算法-leetcode-288. 单词的唯一缩写
算法·leetcode·c#
bugcome_com19 小时前
阿里云 OSS C# SDK 使用实践与参数详解
阿里云·c#
懒人咖1 天前
缺料分析时携带用料清单的二开字段
c#·金蝶云星空
bugcome_com1 天前
深入了解 C# 编程环境及其开发工具
c#