C# 中的方法和参数使用

发布: (2026年2月3日 GMT+8 02:33)
3 min read
原文: Dev.to

Source: Dev.to

定义和调用方法

static void Greet()
{
    Console.WriteLine("Hello!");
}

static void Main()
{
    Greet(); // method call
}
// Output:
Hello!

带参数的方法

static void Greet(string name)
{
    Console.WriteLine("Hello " + name + "!");
}

static void Main()
{
    Greet("Alice");
    Greet("Bob");
}
// Output:
Hello Alice!
Hello Bob!

默认参数

static void PrintMessage(string text = "Default message")
{
    Console.WriteLine(text);
}

static void Main()
{
    PrintMessage("Hello world!");
    PrintMessage();
}
// Output:
Hello world!
Default message

参数 vs 实参

static void Square(int number) // parameter: number
{
    Console.WriteLine(number * number);
}

static void Main()
{
    Square(4); // argument: 4
}
// Output:
16

重载

static int Multiply(int a, int b)
{
    return a * b;
}

static int Multiply(int a, int b, int c)
{
    return a * b * c;
}

static void Main()
{
    Console.WriteLine(Multiply(3, 4));
    Console.WriteLine(Multiply(2, 3, 4));
}
// Output:
12
24

递归

static int Factorial(int n)
{
    if (n <= 1)
        return 1; // base case
    return n * Factorial(n - 1); // recursive call
}

static void Main()
{
    Console.WriteLine(Factorial(5)); // 120
}
// Output:
120

refout 参数

// ref example
static void Increment(ref int number)
{
    number++;
}

// out example
static void ReadValue(out int result)
{
    result = 42;
}

static void Main()
{
    int x = 5;
    Increment(ref x);
    Console.WriteLine(x); // 6

    int y;
    ReadValue(out y);
    Console.WriteLine(y); // 42
}
// Output:
6
42

使用 params 的多个参数

示例:求和

static int Add(params int[] numbers)
{
    int sum = 0;
    foreach (int n in numbers)
        sum += n;
    return sum;
}

static void Main()
{
    Console.WriteLine(Add(1, 2, 3));       // 6
    Console.WriteLine(Add(5, 10, 15, 20)); // 50
}
// Output:
6
50

示例:连接字符串

static string JoinWords(params string[] words)
{
    return string.Join(" ", words);
}

static void Main()
{
    Console.WriteLine(JoinWords("C#", "is", "a", "powerful", "language."));
    // Output: C# is a powerful language.
}
// Output:
C# is a powerful language.

本地函数

static void Main()
{
    int Multiply(int a, int b) // local function
    {
        return a * b;
    }

    Console.WriteLine(Multiply(3, 4)); // 12
}
// Output:
12

  • 方法是可重用的代码块。
  • 参数用于向方法传递数据。
  • return 用于返回值。
  • 默认参数使代码更灵活。
  • 重载允许使用相同名称但不同参数定义方法。
  • refout 参数允许通过引用修改值。
  • params 支持可变数量的参数。
  • 本地函数是定义在另一个方法内部的辅助方法。
  • 递归指方法调用自身来解决问题。
Back to Blog

相关文章

阅读更多 »

C# 14 扩展块

介绍:了解 C# 14 扩展块 https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/extension-methodsdeclare-ex...