亿迅智能制造网
工业4.0先进制造技术信息网站!
首页 | 制造技术 | 制造设备 | 工业物联网 | 工业材料 | 设备保养维修 | 工业编程 |
home  MfgRobots >> 亿迅智能制造网 >  >> Industrial programming >> C语言

C# 方法完全指南:定义、调用、递归与参数传递

方法是一组共同执行任务的语句。每个 C# 程序至少包含一个带有 Main 方法的类。

使用方法需两步:

定义方法

定义方法时声明其结构要素。语法:

<Access Specifier> <Return Type> <Method Name>(Parameter List) {
    Method Body
}

方法要素

示例:FindMax 方法

class NumberManipulator {
    public int FindMax(int num1, int num2) {
        int result;
        if (num1 > num2)
            result = num1;
        else
            result = num2;
        return result;
    }
}

调用方法

通过方法名调用。示例:

using System;
namespace CalculatorApplication {
    class NumberManipulator {
        public int FindMax(int num1, int num2) {
            int result;
            if (num1 > num2) result = num1;
            else result = num2;
            return result;
        }
        
        static void Main(string[] args) {
            int a = 100, b = 200, ret;
            NumberManipulator n = new NumberManipulator();
            ret = n.FindMax(a, b);
            Console.WriteLine("Max value is : {0}", ret);
            Console.ReadLine();
        }
    }
}

输出:

Max value is : 200

也可从其他类通过类实例调用公共方法。

递归方法调用

方法可调用自身,称为递归。示例:计算阶乘

using System;
namespace CalculatorApplication {
    class NumberManipulator {
        public int factorial(int num) {
            if (num == 1) return 1;
            else return factorial(num - 1) * num;
        }
        
        static void Main(string[] args) {
            NumberManipulator n = new NumberManipulator();
            Console.WriteLine("Factorial of 6 is : {0}", n.factorial(6));
            Console.WriteLine("Factorial of 7 is : {0}", n.factorial(7));
            Console.WriteLine("Factorial of 8 is : {0}", n.factorial(8));
            Console.ReadLine();
        }
    }
}

输出:

Factorial of 6 is: 720
Factorial of 7 is: 5040
Factorial of 8 is: 40320

参数传递方式

序号机制及说明
1值参数:将实参实际值复制给形参。函数内修改形参不影响实参。
2引用参数:将实参内存地址引用复制给形参。修改形参影响实参(使用 ref 关键字)。
3输出参数:用于返回多个值(使用 out 关键字)。

参数传递示例

// 值参数
void SwapByValue(int a, int b) { int t = a; a = b; b = t; }

// 引用参数
void SwapByRef(ref int a, ref int b) { int t = a; a = b; b = t; }

// 输出参数
void GetValues(out int a, out int b) { a = 10; b = 20; }

注意:ref 要求实参在传递前已初始化;out 不要求初始化,但方法必须在返回前为所有 out 参数赋值。C# 7.0+ 还支持 in(只读引用)和 ref readonly。

C语言

  1. 精密加工:实现工件精度的核心方法论
  2. 掌握 C# 抽象类与抽象方法:实战指南
  3. 理解 C# 分部类与分部方法
  4. 掌握 C# sealed 类与方法:用法、示例与代码安全性能提升
  5. 掌握 C# 方法重载:核心概念、实战示例与最佳实践
  6. C 语言函数详解:定义、声明、调用与参数传递
  7. C 语言位域:高效内存使用的实战技巧
  8. C 语言可变参数详解:stdarg.h 实战指南
  9. 深入理解 C# 委托:函数引用与事件的完整指南
  10. C# 匿名方法:简化委托使用的实用技巧
  11. MATLAB 积分完全指南:不定/定积分、面积计算与符号/数值方法
  12. Java 8 默认方法:接口演进与向后兼容的关键机制