编写函数重用代码、调试逻辑错误、记录日志、单元测试

编写函数

无返回值的函数

声明为void的函数无返回值,但方法入参out关键字会导致参数通过引用来传递。且可以不用事先声明初始化,可以达到有多个返回值的效果
image.png

using static System.Console;

namespace WritingFunctions
{
    class Porgram
    {
        static void TimesTable(byte number)
        {
            WriteLine($"This is the {number} times table:");
            for (int row = 0; row <= number; row++)
            {
                WriteLine($"{row} ✖️ {number}={row * number}");
            }

            WriteLine();
        }

        static void RunTimesTable()
        {
            bool isNumber;
            do
            {
                Write("Enter a number between 0 and 255: ");
                isNumber = byte.TryParse(ReadLine(), out byte number);
                if (isNumber)
                {
                    TimesTable(number);
                }
                else
                {
                    WriteLine("You did not enter a valid number!");
                }
            } while (isNumber);
        }

        static void Main(string[] args)
        {
            RunTimesTable();
        }
    }
}

有返回值的函数

static void Main(string[] args)
        {
            // RunTimesTable();
            RunCalculateTax();
        }

        static decimal CalculateTax(decimal amount, string twoLetterRegionCode)
        {
            decimal rate = 0.0M;
            switch (twoLetterRegionCode)
            {
                case "CH":
                    rate = 0.08M;
                    break;
                case "DK":
                case "NO":
                    rate = 0.25M;
                    break;
                case "GB":
                case "FR":
                    rate = 0.2M;
                    break;
                case "HU":
                    rate = 0.27M;
                    break;
                case "OR":
                case "AK":
                case "MT":
                    rate = 0.0M;
                    break;
                case "ND":
                case "WI":
                case "ME":
                case "VA":
                    rate = 0.05M;
                    break;
                case "CA":
                    rate = 0.0825M;
                    break;
                default:
                    rate = 0.06M;
                    break;
            }

            return amount * rate;
        }

        static void RunCalculateTax()
        {
            Write("Enter an amount: ");
            string amountInText = ReadLine();

            Write("Enter a two-letter region code: ");
            string region = ReadLine();
            if (decimal.TryParse(amountInText, out decimal amount))
            {
                decimal taxToPay = CalculateTax(amount, region);
                WriteLine($"You must pay {taxToPay} in sales tax.");
            }
            else
            {
                WriteLine("You did not enter a valid amount!");
            }
        }
  • 将序数转为基数
//将序数转为基数
        static void RunCalculateTax()
        {
            Write("Enter an amount: ");
            string amountInText = ReadLine();

            Write("Enter a two-letter region code: ");
            string region = ReadLine();
            if (decimal.TryParse(amountInText, out decimal amount))
            {
                decimal taxToPay = CalculateTax(amount, region);
                WriteLine($"You must pay {taxToPay} in sales tax.");
            }
            else
            {
                WriteLine("You did not enter a valid amount!");
            }
        }

        //编写数学函数
        static string CardinalToOrdinal(int number)
        {
            if (number==22)
            {
                int a;
            }
            switch (number)
            {
                case 11:
                case 12:
                case 13:
                    return $"{number}th";
                default:
                    int lastDigit = number % 10;
                    string suffix = lastDigit switch
                    {
                        1 => "st",
                        2 => "nd",
                        3 => "rd",
                        _ => "th"
                    };
                    return $"{number}{suffix}";
            }
        }
        static void RunCardinalToOrdinal()
        {
            for (int number = 1; number <= 40; number++)
            {
                Write($"{CardinalToOrdinal(number)}");
            }
            WriteLine();
        }

使用xml进行注释文档解释函数

        /// <summary>
        /// 将序数转为基数
        /// </summary>

函数中使用lambda

个人感觉C#的lambda比java更好,C#可以传递lambda表达式方法本身,而java只能传递入参。即必须要另外写Functional相关接口逻辑。但是由于stream流底层以及写好很多闭包方法,也还可以吧。
一下俩个方法等价

//函数式接口
        static int FibImperative(int term)
        {
            if (term == 1)
            {
                return 0;
            }
            else if (term == 2)
            {
                return 1;
            }
            else
            {
                return FibImperative(term - 1) + FibImperative(term - 2);
            }
        }

        static int FibFunctional(int term) => term switch
        {
            1 => 0,
            2 => 1,
            _ => FibFunctional(term - 1) + FibFunctional(term - 2)
        };


        static void RunFibImperative()
        {
            for (int i = 1; i <= 30; i++)
            {
                // WriteLine($"The {CardinalToOrdinal(i)} term of the Fibonacci sequence is {FibImperative(term: i):N0}");
                WriteLine($"The {CardinalToOrdinal(i)} term of the Fibonacci sequence is {FibFunctional(term: i):N0}");
            }
        }

日志记录

Debug和Trace

可以将输出写入任何跟踪监听器
Debug用于开发过程、Trace用于开发和运行时,下面代码会生在项目目录下生成log.txt打印记录的日志

            Trace.Listeners.Add(new TextWriterTraceListener(File.Create("log.txt")));
            Trace.AutoFlush = true;
            Debug.WriteLine("Debug says,I am watching!");
            Trace.WriteLine("Trace says,I am watching!");

日志记录级别

  • Off 关闭日志
  • Error 只记录错误日志
  • Warning 只记录错误、警告
  • Info 输出错误、警告、信息
  • Verbose 输出所有日志信息

单元测试


这个家伙很懒,啥也没有留下😋