跳转到内容

C Sharp 方法文档

来自代码酷

C#方法文档[编辑 | 编辑源代码]

C#方法是C#编程语言中的基本构建块之一,用于封装可重用的代码逻辑。方法允许开发者将功能分解为独立的单元,从而提高代码的可读性、可维护性和复用性。本文档将详细介绍C#方法的语法、类型、参数传递、重载及实际应用。

方法的基本概念[编辑 | 编辑源代码]

在C#中,方法(Method)是一段具有名称的代码块,用于执行特定任务。方法可以接受输入参数,并可能返回一个值。方法的主要组成部分包括:

  • 访问修饰符(如public、private等)
  • 返回类型(如void、int等)
  • 方法名称
  • 参数列表(可选)
  • 方法体(包含实际执行的代码)

基本语法[编辑 | 编辑源代码]

访问修饰符 返回类型 方法名称(参数列表)
{
    // 方法体
}

方法的类型[编辑 | 编辑源代码]

C#支持多种类型的方法,每种类型适用于不同的场景。

1. 实例方法[编辑 | 编辑源代码]

实例方法属于类的实例,必须通过对象调用。

public class Calculator
{
    public int Add(int a, int b)  // 实例方法
    {
        return a + b;
    }
}

// 调用
Calculator calc = new Calculator();
int result = calc.Add(5, 3);  // 输出: 8

2. 静态方法[编辑 | 编辑源代码]

静态方法属于类本身而非实例,使用`static`关键字声明。

public class MathUtility
{
    public static double Square(double number)  // 静态方法
    {
        return number * number;
    }
}

// 调用
double squared = MathUtility.Square(4.5);  // 输出: 20.25

3. 虚方法与重写方法[编辑 | 编辑源代码]

虚方法(`virtual`)允许子类重写(`override`)其实现。

public class Animal
{
    public virtual void MakeSound()  // 虚方法
    {
        Console.WriteLine("Some sound");
    }
}

public class Dog : Animal
{
    public override void MakeSound()  // 重写方法
    {
        Console.WriteLine("Bark");
    }
}

// 调用
Animal myDog = new Dog();
myDog.MakeSound();  // 输出: Bark

方法参数[编辑 | 编辑源代码]

C#方法支持多种参数传递方式:

1. 值参数(默认)[编辑 | 编辑源代码]

参数值被复制到方法中。

public void Increment(int num)
{
    num++;
    Console.WriteLine(num);  // 输出: 6
}

int value = 5;
Increment(value);
Console.WriteLine(value);  // 输出: 5 (原始值未改变)

2. 引用参数(ref)[编辑 | 编辑源代码]

使用`ref`关键字传递变量引用。

public void Increment(ref int num)
{
    num++;
}

int value = 5;
Increment(ref value);
Console.WriteLine(value);  // 输出: 6 (原始值已改变)

3. 输出参数(out)[编辑 | 编辑源代码]

使用`out`关键字返回多个值。

public void Divide(int dividend, int divisor, out int quotient, out int remainder)
{
    quotient = dividend / divisor;
    remainder = dividend % divisor;
}

int q, r;
Divide(10, 3, out q, out r);
Console.WriteLine($"商: {q}, 余数: {r}");  // 输出: 商: 3, 余数: 1

4. 参数数组(params)[编辑 | 编辑源代码]

使用`params`关键字接受可变数量的参数。

public int Sum(params int[] numbers)
{
    int total = 0;
    foreach (int num in numbers)
    {
        total += num;
    }
    return total;
}

int result = Sum(1, 2, 3, 4, 5);  // 输出: 15

方法重载[编辑 | 编辑源代码]

方法重载允许在同一类中定义多个同名方法,只要它们的参数列表不同。

public class Printer
{
    public void Print(string text)  // 版本1
    {
        Console.WriteLine(text);
    }

    public void Print(int number)  // 版本2
    {
        Console.WriteLine(number.ToString());
    }

    public void Print(string text, int times)  // 版本3
    {
        for (int i = 0; i < times; i++)
        {
            Console.WriteLine(text);
        }
    }
}

// 调用
Printer printer = new Printer();
printer.Print("Hello");          // 调用版本1
printer.Print(42);               // 调用版本2
printer.Print("C#", 3);          // 调用版本3

实际应用案例[编辑 | 编辑源代码]

案例1:电子商务系统中的折扣计算[编辑 | 编辑源代码]

public class DiscountCalculator
{
    // 计算固定折扣
    public decimal CalculateDiscount(decimal price, decimal discountRate)
    {
        return price * (1 - discountRate);
    }

    // 计算阶梯折扣
    public decimal CalculateDiscount(decimal price, int quantity, decimal[] discountRates)
    {
        if (quantity <= 0) return price;
        int tier = Math.Min(quantity, discountRates.Length) - 1;
        return price * (1 - discountRates[tier]);
    }
}

// 使用示例
var calculator = new DiscountCalculator();
decimal finalPrice1 = calculator.CalculateDiscount(100.0m, 0.2m);  // 8折
decimal finalPrice2 = calculator.CalculateDiscount(100.0m, 3, new[] { 0.1m, 0.15m, 0.2m });  // 第3档折扣

案例2:游戏角色状态更新[编辑 | 编辑源代码]

public class GameCharacter
{
    private int health;
    
    // 恢复生命值
    public void Heal(int amount)
    {
        health = Math.Min(100, health + amount);
        Console.WriteLine($"恢复 {amount} 点生命,当前生命值: {health}");
    }

    // 受到伤害
    public void TakeDamage(int damage, bool isCritical = false)
    {
        int actualDamage = isCritical ? damage * 2 : damage;
        health = Math.Max(0, health - actualDamage);
        Console.WriteLine($"受到 {(isCritical ? "暴击 " : "")}伤害: {actualDamage}, 剩余生命值: {health}");
    }
}

// 使用示例
var hero = new GameCharacter { Health = 80 };
hero.TakeDamage(30);          // 普通伤害
hero.TakeDamage(20, true);    // 暴击伤害
hero.Heal(25);                // 恢复生命

方法调用流程[编辑 | 编辑源代码]

graph TD A[调用方法] --> B[参数评估] B --> C[创建新的栈帧] C --> D[参数传递] D --> E[执行方法体] E --> F[返回值处理] F --> G[销毁栈帧] G --> H[控制权返回调用者]

最佳实践[编辑 | 编辑源代码]

1. 单一职责原则: 每个方法应只完成一个明确的任务 2. 合理命名: 方法名应清晰表达其功能(动词+名词,如`CalculateTax`) 3. 参数数量控制: 避免过多参数(通常不超过4-5个) 4. 适当长度: 方法体不宜过长(建议不超过一屏) 5. 异常处理: 在方法中妥善处理可能出现的异常

性能考虑[编辑 | 编辑源代码]

  • 频繁调用的简单方法可考虑标记为`inline`(通过JIT编译器优化)
  • 避免在循环中创建大量临时对象的方法
  • 对于性能关键代码,可考虑使用`ref`参数减少复制开销

数学方法示例[编辑 | 编辑源代码]

以下示例展示如何在C#方法中实现数学公式:

计算二次方程的根: ax2+bx+c=0

public static (double? root1, double? root2) SolveQuadratic(double a, double b, double c)
{
    double discriminant = b * b - 4 * a * c;
    
    if (discriminant < 0)
        return (null, null);  // 无实数根
    
    double sqrtDiscriminant = Math.Sqrt(discriminant);
    double root1 = (-b + sqrtDiscriminant) / (2 * a);
    double root2 = (-b - sqrtDiscriminant) / (2 * a);
    
    return (root1, root2);
}

// 使用示例
var roots = SolveQuadratic(1, -3, 2);  // x² -3x +2 =0
Console.WriteLine($"根1: {roots.root1}, 根2: {roots.root2}");  // 输出: 根1: 2, 根2: 1

总结[编辑 | 编辑源代码]

C#方法是构建程序逻辑的核心元素。通过合理使用方法的各种特性(如重载、参数传递方式、静态/实例方法等),可以创建出结构良好、易于维护的代码。掌握方法的设计和使用技巧是成为高效C#开发者的关键一步。