CSharp-Learning/notes/04_Methods_and_Classes.md
Rosmontis_Cloud f604d53191 Initial commit: C# 学习笔记和示例代码
- Lesson 01-10: C# 基础语法
- WebView2: 集成示例
- notes/: 详细笔记
2026-07-01 16:31:35 +08:00

92 lines
1.4 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# 第四课:方法(函数)和类
## 方法(函数)
```csharp
// 无返回值
void SayHello(string name)
{
Console.WriteLine($"你好, {name}");
}
// 有返回值
int Add(int a, int b)
{
return a + b;
}
// 带默认参数
void Greet(string name = "World")
{
Console.WriteLine($"Hello, {name}");
}
```
## 方法调用
```csharp
static void Main(string[] args)
{
SayHello("无言势"); // 调用无返回值方法
int sum = Add(1, 2); // 调用有返回值方法
Console.WriteLine(sum); // 输出 3
}
```
## 类Class
```csharp
class Person
{
// 字段(属性)
public string name;
public int age;
// 构造函数
public Person(string name, int age)
{
this.name = name;
this.age = age;
}
// 方法
public void SayHi()
{
Console.WriteLine($"我是{name},今年{age}岁");
}
}
```
## 创建对象
```csharp
static void Main(string[] args)
{
Person p = new Person("无言势", 25);
p.SayHi();
}
```
## 访问修饰符
| 修饰符 | 访问范围 |
|--------|----------|
| `public` | 任何地方都能访问 |
| `private` | 只有本类内部能访问 |
| `internal` | 同程序集内访问 |
## 静态static
```csharp
class MathHelper
{
public static int Add(int a, int b)
{
return a + b;
}
}
// 调用不需要 new
int result = MathHelper.Add(1, 2);
```