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

1.4 KiB
Raw Permalink Blame History

第四课:方法(函数)和类

方法(函数)

// 无返回值
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}");
}

方法调用

static void Main(string[] args)
{
    SayHello("无言势");      // 调用无返回值方法
    int sum = Add(1, 2);   // 调用有返回值方法
    Console.WriteLine(sum); // 输出 3
}

Class

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}岁");
    }
}

创建对象

static void Main(string[] args)
{
    Person p = new Person("无言势", 25);
    p.SayHi();
}

访问修饰符

修饰符 访问范围
public 任何地方都能访问
private 只有本类内部能访问
internal 同程序集内访问

静态static

class MathHelper
{
    public static int Add(int a, int b)
    {
        return a + b;
    }
}

// 调用不需要 new
int result = MathHelper.Add(1, 2);