蓝色天空.知识 · 实践 · 创造
我的收藏
在线代码实验室

在本地 csc4(C# 5.0)实测方法定义、值/ref/out 传参、递归、命名默认参数与重载

CSHARPWindows x64、.NET Framework 4.x Visual C# 编译器(csc.exe)本地离线环境。ExploreMethods.cs
ExploreMethods.cs242 行
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Text;

namespace CSharpMethodsLab
{
    internal class NumberHelper
    {
        public int FindMax(int num1, int num2)
        {
            if (num1 > num2)
            {
                return num1;
            }
            return num2;
        }
    }

    internal class Calculator
    {
        public int Add(int a, int b)
        {
            return a + b;
        }

        public int Add(int a, int b, int c)
        {
            return a + b + c;
        }

        public double Add(double a, double b)
        {
            return a + b;
        }
    }

    internal class Program
    {
        private static void SwapByValue(int x, int y, out int innerX, out int innerY)
        {
            int temp = x;
            x = y;
            y = temp;
            innerX = x;
            innerY = y;
        }

        private static void SwapByRef(ref int x, ref int y)
        {
            int temp = x;
            x = y;
            y = temp;
        }

        private static void GetPairValues(out int x, out int y)
        {
            x = 15;
            y = 25;
        }

        private static bool TryDivide(int a, int b, out double result)
        {
            if (b == 0)
            {
                result = 0.0;
                return false;
            }
            result = (double)a / b;
            return true;
        }

        private static int Factorial(int n)
        {
            if (n <= 1)
            {
                return 1;
            }
            return n * Factorial(n - 1);
        }

        private static double Power(double baseNum, int power = 2)
        {
            double result = 1.0;
            for (int i = 0; i < power; i++)
            {
                result *= baseNum;
            }
            return result;
        }

        private static string FormatInfo(string name, int age = 18, string city = "未知")
        {
            return string.Format("{0}, {1}岁, {2}", name, age, city);
        }

        private static string Esc(string s)
        {
            if (s == null) return "null";
            StringBuilder sb = new StringBuilder("\"");
            foreach (char c in s)
            {
                switch (c)
                {
                    case '\\': sb.Append("\\\\"); break;
                    case '"': sb.Append("\\\""); break;
                    case '\n': sb.Append("\\n"); break;
                    case '\r': sb.Append("\\r"); break;
                    case '\t': sb.Append("\\t"); break;
                    default:
                        if (c < 32) sb.AppendFormat("\\u{0:x4}", (int)c);
                        else sb.Append(c);
                        break;
                }
            }
            sb.Append("\"");
            return sb.ToString();
        }

        private static string CaseJson(string name, string summary, string expected, string actual)
        {
            bool passed = string.Equals(expected, actual, StringComparison.Ordinal);
            return string.Format(
                "{{\"name\":{0},\"summary\":{1},\"expected\":{2},\"actual\":{3},\"passed\":{4}}}",
                Esc(name), Esc(summary), Esc(expected), Esc(actual), passed ? "true" : "false"
            );
        }

        private static void Main(string[] args)
        {
            Console.OutputEncoding = Encoding.UTF8;
            List<string> cases = new List<string>();

            // Case 1: Method definition & cross-class invocation (FindMax)
            NumberHelper helper = new NumberHelper();
            int max1 = helper.FindMax(100, 200);
            int max2 = helper.FindMax(350, 120);
            string actual1 = string.Format("max1={0},max2={1}", max1, max2);
            cases.Add(CaseJson(
                "method_definition_and_call",
                "验证方法定义、跨类实例化调用 FindMax 以及参数传递与返回值流程",
                "max1=200,max2=350",
                actual1
            ));

            // Case 2: Pass by value vs ref
            int a = 100;
            int b = 200;
            int innerX;
            int innerY;
            SwapByValue(a, b, out innerX, out innerY);
            int afterValA = a;
            int afterValB = b;
            SwapByRef(ref a, ref b);
            string actual2 = string.Format(
                "val_inner={0}/{1},val_after={2}/{3},ref_after={4}/{5}",
                innerX, innerY, afterValA, afterValB, a, b
            );
            cases.Add(CaseJson(
                "pass_by_value_and_ref",
                "对比按值传递(形参副本互换不影响实参)与 ref 按引用传递(直接修改调用方变量)",
                "val_inner=200/100,val_after=100/200,ref_after=200/100",
                actual2
            ));

            // Case 3: out parameters and TryDivide / int.TryParse pattern
            int outA;
            int outB;
            GetPairValues(out outA, out outB);
            double divOkVal;
            bool divOk = TryDivide(10, 3, out divOkVal);
            double divZeroVal;
            bool divZero = TryDivide(10, 0, out divZeroVal);
            int parsedNum;
            bool parsedOk = int.TryParse("123", out parsedNum);
            string actual3 = string.Format(
                CultureInfo.InvariantCulture,
                "pair={0}/{1},divOk={2}:{3:F2},divZero={4}:{5:F0},parse={6}:{7}",
                outA, outB, divOk, divOkVal, divZero, divZeroVal, parsedOk, parsedNum
            );
            cases.Add(CaseJson(
                "out_parameters_and_try_pattern",
                "验证 out 输出参数返回多值以及 TryDivide 与 int.TryParse 安全解析模式",
                "pair=15/25,divOk=True:3.33,divZero=False:0,parse=True:123",
                actual3
            ));

            // Case 4: Recursion (Factorial)
            string actual4 = string.Format(
                "f0={0},f4={1},f6={2},f7={3},f8={4}",
                Factorial(0), Factorial(4), Factorial(6), Factorial(7), Factorial(8)
            );
            cases.Add(CaseJson(
                "recursive_factorial",
                "验证递归基准条件与递归步骤:0!、4!、6!、7!、8! 计算结果",
                "f0=1,f4=24,f6=720,f7=5040,f8=40320",
                actual4
            ));

            // Case 5: Optional (default) parameters & named arguments
            double pDef = Power(3);
            double pExp = Power(3, 3);
            string info1 = FormatInfo("小明", city: "北京");
            string info2 = FormatInfo(city: "上海", name: "小红", age: 25);
            string actual5 = string.Format(
                CultureInfo.InvariantCulture,
                "p2={0:F1},p3={1:F1},i1={2},i2={3}",
                pDef, pExp, info1, info2
            );
            cases.Add(CaseJson(
                "optional_and_named_parameters",
                "验证默认参数省略调用与命名参数跳过或乱序传参",
                "p2=9.0,p3=27.0,i1=小明, 18岁, 北京,i2=小红, 25岁, 上海",
                actual5
            ));

            // Case 6: Method overloading
            Calculator calc = new Calculator();
            int sum2 = calc.Add(1, 2);
            int sum3 = calc.Add(1, 2, 3);
            double sumD = calc.Add(1.5, 2.5);
            string actual6 = string.Format(
                CultureInfo.InvariantCulture,
                "int2={0},int3={1},double2={2:F1}",
                sum2, sum3, sumD
            );
            cases.Add(CaseJson(
                "method_overloading",
                "验证同类中基于参数个数与参数类型区分的 Add 方法重载决议",
                "int2=3,int3=6,double2=4.0",
                actual6
            ));

            Console.WriteLine(string.Format(
                "{{\"version\":{0},\"cases\":[{1}]}}",
                Esc("CLR " + Environment.Version.ToString()),
                string.Join(",", cases.ToArray())
            ));
        }
    }
}
本例需在 Windows x64、.NET Framework 4.x Visual C# 编译器(csc.exe)本地离线环境。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程

运行环境:Windows x64、.NET Framework 4.x Visual C# 编译器(csc.exe)本地离线环境。

入口文件:projects/csharp-methods-lab/ExploreMethods.cs

本地运行步骤快速上手
  1. 点击上方“保存源码”保存为 ExploreMethods.cs,或下载右侧课程工程包。
  2. 确认本地已准备 Windows x64、.NET Framework 4.x Visual C# 编译器(csc.exe)本地离线环境。。
  3. 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载

下载课程关联工程包:C#

课程关联工程包(登记关联42章) · 含当前章节或实例 · mbskycom202612a1321.zip

下载课程关联工程包:C#

课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a1341.zip
SITE SEARCH

搜索教程、工具与资讯

热门搜索

JavaScriptJSON格式化正则表达式AI 编程AI 翻译AI导航专题标签
Esc 关闭

欢迎登录蓝色天空网

使用会员账号,继续你的学习