C# 基础语法与面向对象核心:类、成员、实例化、标识符与关键字
C# 是面向对象语言:程序由对象组成,对象通过方法交互。同类对象共享类型定义。
矩形类实战示例
using System;
namespace RectangleApplication {
class Rectangle {
double length, width; // 成员变量
public void Acceptdetails() { length=4.5; width=3.5; }
public double GetArea() { return length*width; }
public void Display() {
Console.WriteLine("Length: {0}", length);
Console.WriteLine("Width: {0}", width);
Console.WriteLine("Area: {0}", GetArea());
}
}
class ExecuteRectangle {
static void Main(string[] args) {
Rectangle r = new Rectangle(); // 实例化
r.Acceptdetails(); r.Display(); Console.ReadLine();
}
}
}
输出:Length: 4.5 Width: 3.5 Area: 15.75
核心语法要素
- using:引入命名空间,首行通常 using System;
- class:声明类
- 注释:/*...*/ 多行,// 单行
- 成员变量:类的数据字段(如 length/width)
- 成员函数:类内声明的功能方法(Acceptdetails/GetArea/Display)
- 实例化:new ClassName() 创建对象
标识符命名规则
- 首字符必须为字母或下划线,后接字母/数字/下划线
- 不能包含空格或符号 ?-+!@#%^&*()[]{}.;:'"/\ 等
- 不能是 C# 保留关键字(可加 @ 前缀强制使用)
C# 关键字完整表
| 保留关键字 (78个) | ||||||
|---|---|---|---|---|---|---|
| abstract | as | base | bool | break | byte | case |
| catch | char | checked | class | const | continue | decimal |
| default | delegate | do | double | else | enum | event |
| explicit | extern | false | finally | fixed | float | for |
| foreach | goto | if | implicit | in | in(generic) | int |
| interface | internal | is | lock | long | namespace | new |
| null | object | operator | out | out(generic) | override | params |
| private | protected | public | readonly | ref | return | sbyte |
| sealed | short | sizeof | stackalloc | static | string | struct |
| switch | this | throw | true | try | typeof | uint |
| ulong | unchecked | unsafe | ushort | using | virtual | void |
| volatile | while | |||||
| 上下文关键字 (13个) | ||||||
| add | alias | ascending | descending | dynamic | from | get |
| global | group | into | join | let | orderby | partial(type) |
| partial(method) | remove | select | set | |||
C语言
- C++ 类模板实战指南:编写灵活的类型无关代码
- C 语言存储类完全解析:auto、extern、static、register
- C 语言基础语法精通:Token、分号、注释与标识符规范
- C++核心语法与面向对象基石深度解析
- C++多态实战指南:虚函数、动态绑定与纯虚函数
- C++数据抽象实战:接口与实现分离的设计艺术
- C++数据封装:守护代码安全的核心机制
- C# 程序结构解析:从 Hello World 看命名空间、类、Main 入口与编译运行
- C# 封装详解:访问修饰符与面向对象设计最佳实践
- C# 类完全指南:定义、封装、构造函数、析构函数与静态成员
- MATLAB 基础语法速成:交互计算、变量、运算符、格式控制与注释
- Java 基础:掌握基本语法