c#第七天方法2

这篇博客详细介绍了C#中方法的调用者与被调用者的关系,包括如何通过参数传递值,重点讲解了ref、out参数的使用,方法的返回值、重载以及递归的概念。此外,还提供了多个练习来巩固这些知识点。

调用者和被调用者的关系

1.调用者和被调用者的关系
我们在Main()函数中调用Test()函数,
我们管Main()函数叫做调用者,管Test()函数叫做调用者,管Test
被调用者。
如果被调用者想要得到调用者中的值:
1、传递参数
2、声明一个静态的字段,当做"全局变量"使用。

如果调用者想要得到被调用者中的值:
1、写返回值。
形参:形式上的参数,也会在内存中开辟空间。
实参:调用函数的时候传入的参数。
问题:形参和实参的名字必须一样么?

5、在写方法的时候需要注意
1、方法的功能一定要单一。
2、在方法中尽量的避免出现提示用户输入之类的代码。

1、ref参数
ref参数侧重于将一个变量以参数的形式带到一个方法中进行改变,
改变完成后,再讲改变后的值带出来。
在使用ref参数的时候需要注意:ref参数在方法外必须为其赋值。

2、方法的重载
方法的重载指的是方法的名称相同,但是参数不同。
参数不同:
1)、如果参数的个数相同,那么参数的类型就不能相同。
2)、如果参数的类型相同,那么参数的个数就不能相同。

方法的重载跟返回值没有关系。

3、方法的总结
1、作用:可以让代码重复的使用
2、参数:完成这个方法所必须要的条件
3、返回值:完成方法后,方法返回的结果
4、out参数:可以让方法返回多个值
5、ref参数:侧重于将一个变量带到方法中进行改变,改变完成后,再讲改变后的值带出去。
6、params可变参数:将实参列表中跟可变参数数组类型一样的参数当做是可变参数数组中的元素。
可变参数必须形参列表中的最后一个元素
7、方法的重载:
方法的名称相同,但是参数不同。跟返回值没关系。
参数不同:
1)、如果参数的个数相同,那么参数的类型就不能相同。
2)、如果参数的类型相同,那么参数的个数就不能相同。
8、方法的递归:自己在方法中调用自己。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace _08_调用者和被调用者的关系
{
    class Program
    {

//        我们在Main()函数中调用Test()函数,
//我们管Main()函数叫做调用者,管Test()函数叫做调用者,管Test
//被调用者。
//如果被调用者想要得到调用者中的值:
//1、传递参数
//2、声明一个静态的字段,当做"全局变量"使用。
        public static int _a = 3;//用来模拟全局变量
        static void Main(string[] args)
        {
            int a = 3;
            int aNew = Test(a);//实参
            Console.WriteLine(aNew);
            Console.ReadKey();
        }

//        如果调用者想要得到被调用者中的值:
//1、写返回值。

//形参:形式上的参数,也会在内存中开辟空间。
//实参:调用函数的时候传入的参数。
//问题:形参和实参的名字必须一样么?

        public static int Test(int a)//形参
        {
            a = a + 5;
            return a;
        }
        public static void TestTwo()
        {

        }

        public static void TestThree()
        {

        }
    }
}

使用方法来判断是否是闰年

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace _09_使用方法来判断闰年
{
    class Program
    {
        static void Main(string[] args)
        {
            //写一个方法,判断你给的年份是否是闰年 true false bool类型
            //需要给一个年份作为参数
            Console.WriteLine("请输入一个年份");
            int year = Convert.ToInt32(Console.ReadLine());
            bool b = IsRun(year);
            Console.WriteLine(b);
            Console.ReadKey();
        }



        /// <summary>
        /// 判断给定的年份是否是闰年
        /// </summary>
        /// <param name="year">要判断的年份</param>
        /// <returns>是否是闰年</returns>
        public static bool IsRun(int year)
        {
            //if ((year % 400 == 0) || (year % 4 == 0 && year % 100 != 0))
            //{
            //    return true;
            //}
            //else
            //{
            //    return false;
            //}

            return (year % 400 == 0) || (year % 4 == 0 && year % 100 != 0) ? true : false;
        }

    }
}

方法四个练习

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace _10_方法的4个练习题
{
    class Program
    {
        static void Main(string[] args)
        {
            //1 读取输入的整数,定义成方法,
            //多次调用(如果用户输入的是数字,则返回,否则提示用户重新输入)
            //Console.WriteLine("请输入一个数字");
            //string str = Console.ReadLine();
            //int n = GetNumber(str);
            //Console.WriteLine(n);
            //Console.ReadKey();

            //还记得学循环时做的那道题吗?只允许用户输入y或n,请改成方法

            //Console.WriteLine("请输入yes或者no");
            //string str = Console.ReadLine();
            //string strNew = IsYorN(str);
            //Console.WriteLine("您输入的是{0}",strNew);
            //Console.ReadKey();



            //3查找两个整数中的最大值:int Max(int i1,int i2)


            //计算输入数组的和:int Sum(int[] values)
            int[] nums = { 1, 2, 3, 4, 5, 6 };
            int sum = GetSum(nums);
            Console.WriteLine(sum);
            Console.ReadKey();


        }

        public static int GetSum(int[] n)
        {
            int sum = 0;
            for (int i = 0; i < n.Length; i++)
            {
                sum += n[i];
            }
            return sum;
        }

        /// <summary>
        /// 判断用户输入的是否是yes或者no,只要不是,就重新输入
        /// </summary>
        /// <param name="input">要判断的字符串</param>
        /// <returns>yes或者no</returns>
        public static string IsYorN(string input)
        {
            while (true)
            {
                if (input != "yes" && input != "no")
                {
                    Console.WriteLine("输入有误,只能输入yes或者no");
                    input = Console.ReadLine();
                }
                else
                {
                    return input;
                }
            }
        }




        /// <summary>
        /// 将用户输入的字符串转换成int类型
        /// </summary>
        /// <param name="strNumber">用户输入的字符串</param>
        /// <returns>返回转换成功后的整数</returns>
        public static int GetNumber(string strNumber)//数字  乱七八糟
        {
            while (true)
            {
                try
                {
                    int number = Convert.ToInt32(strNumber);
                    return number;
                }
                catch
                {
                    Console.WriteLine("输入有误,请重新输入");
                    strNumber = Console.ReadLine();
                }
            }

        }


    }
}

让方法返回多个值

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace _11_让方法返回多个值
{
    class Program
    {
        static void Main(string[] args)
        {
            
            //写一个方法 让这个方法返回一个数组的最大值、最小值、总和、平均值
            int[] nums = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
            int[] numsNew = GetMaxMinSumAvg(nums);
            Console.WriteLine("这个数组的最大值是{0},最小值是{1},总和是{2},平均值是{3}",numsNew[0],numsNew[1],numsNew[2],numsNew[3]);
            Console.ReadKey();
        }


        /// <summary>
        /// 返回一个数组的最大值、最小值、总和、平均值
        /// </summary>
        /// <param name="nums"></param>
        /// <returns></returns>
        public static int[] GetMaxMinSumAvg(int[] nums)//string double bool
        {
            int[] numsNew = new int[4];
            //numsNew[0]最大值  numsNew[1]最小值 numsNew[2]总和 numsNew[3]平均值
            numsNew[0] = nums[0];//int max=nums[0]
            numsNew[1] = nums[0];//int min=nums[0]
            numsNew[2] = 0;
            for (int i = 0; i < nums.Length; i++)
            {
                if (nums[i] > numsNew[0])
                {
                    numsNew[0] = nums[i];
                }
                if (nums[i] < numsNew[1])
                {
                    numsNew[1] = nums[i];
                }
                numsNew[2] += nums[i];
            }
            numsNew[3] = numsNew[2] / nums.Length;
            return numsNew;
        }

    }
}

6、out参数

可以帮助我们在一个方法中返回多个值,不限类型。
使用out参数的时候要求,out参数必须在方法内为其赋值。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace _12out参数
{
    class Program
    {
        static void Main(string[] args)
        {
            int n;
            bool b;
            string s = Test(out n, out b);
            Console.WriteLine(s);
            Console.WriteLine(n);
            Console.WriteLine(b);
            Console.ReadKey();
        }

        public static string Test(out int number, out bool b)//我想再返回一个int类型的100
        {
            number = 100;
            b = false;
            return "张三";
        }
    }
}

out参数练习

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace _13out参数练习
{
    class Program
    {
        static void Main(string[] args)
        {
            //写一个方法判断用户是否登陆成功
            //如果登陆成功返回一个true,并且返回一条登陆信息
            //如果登陆失败 返回一个false 返回一条错误信息
            Console.WriteLine("请输入用户名");
            string name = Console.ReadLine();
            Console.WriteLine("请输入密码");
            string pwd = Console.ReadLine();
            string msg;
            bool b = IsLogin(name, pwd, out msg);
            Console.WriteLine("登陆结果:{0}", b);
            Console.WriteLine("登陆信息:{0}",msg);
            Console.ReadKey();
        }

        /// <summary>
        /// 判断登陆是否成功
        /// </summary>
        /// <param name="userName">用户输入的用户名</param>
        /// <param name="userPwd">密码</param>
        /// <param name="msg">多余要返回的登陆信息</param>
        /// <returns>登陆是否成功</returns>
        public static bool IsLogin(string userName, string userPwd, out string msg)
        {
            if (userName == "admin" && userPwd == "admin")
            {
                msg = "登陆成功";
                return true;
            }
            else if (userName == "admin")
            {
                msg = "密码错误";
                return false;
            }
            else if (userPwd == "admin")
            {
                msg = "用户名错误";
                return false;
            }
            else
            {
                msg = "未知错误";
                return false;
            }
        }
    }
}

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace _14out参数练习
{
    class Program
    {
        static void Main(string[] args)
        {
            //使用out参数返回一个数组的最大值、最小值、总和、平均值
            int[] nums = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
            int max;
            int min;
            int sum;
            int avg;
            GetMaxMinSumAvg(nums, out  max, out min, out sum, out avg);
            Console.WriteLine(max);
            Console.WriteLine(min);
            Console.WriteLine(sum);
            Console.WriteLine(avg);
            Console.ReadKey();
        }

        public static void GetMaxMinSumAvg(int[] nums, out int max, out int min, out int sum, out int avg)
        {
            max = nums[0];
            min = nums[0];
            sum = 0;
            for (int i =0; i < nums.Length; i++)
            {
                if (nums[i] > max)
                {
                    max = nums[i];
                }
                if (nums[i] < min)
                {
                    min = nums[i];
                }
                sum += nums[i];
            }
            avg = sum / nums.Length;
        }
    }
}

自动动手写TryParse

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace _15自动动手写TryParse
{
    class Program
    {
        static void Main(string[] args)
        {
            // int.TryParse()
            int result = 100;
            bool b = MyTryParse("123abc", out result);
            Console.WriteLine(b);
            Console.WriteLine(result);
            Console.ReadKey();
            //无--有   总结
            //有--很多
        }



        /// <summary>
        /// 将字符串转换成int类型
        /// </summary>
        /// <param name="s">要转换的字符串</param>
        /// <param name="result">转换成功后的整数</param>
        /// <returns></returns>
        public static bool MyTryParse(string s, out int result)
        {
            try
            {
                result = Convert.ToInt32(s);
                return true;
            }
            catch
            {
                result = 0;
                return false;
            }
        }
    }
}

1、ref参数

ref参数侧重于将一个变量以参数的形式带到一个方法中进行改变,
改变完成后,再将改变后的值带出来。
在使用ref参数的时候需要注意:ref参数在方法外必须为其赋值。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace _01ref参数
{
    class Program
    {
        static void Main(string[] args)
        {
            //out参数  侧重于让方法返回多个值  必须在方法内赋值
            //ref 参数
            double salary = 5000;
            JiangJin(ref salary);
            Console.WriteLine(salary);
            Console.ReadKey();
        }

        public static void JiangJin(ref double s)
        {
            s += 500;
        }

        public static void FaKuan(double s)
        {
            s -= 500; ;
        }

    }
}

ref参数练习

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace _02ref参数练习
{
    class Program
    {
        static void Main(string[] args)
        {
            //交换两个int类型的变量
            int n1 = 10;
            int n2 = 20;
            //int temp = n1;
            //n1 = n2;
            //n2 = temp;



            //n1 = n1 - n2;
            //n2 = n1 + n2;
            //n1 = n2 - n1;
            //Console.WriteLine(n1);
            //Console.WriteLine(n2);
            // Change(out n1, out n2);

            Change(ref n1, ref  n2);
            Console.WriteLine(n1);
            Console.WriteLine(n2);
            Console.ReadKey();
        }

        public static void Change(ref  int n1, ref int n2)
        {
            int temp = n1;
            n1 = n2;
            n2 = temp;
        }
    }
}

out在方法类中可以返货多个值
而ref把外面的值带到方法里改变,改变之后在带main里面去

2、方法的重载

方法的重载指的是方法的名称相同,但是参数不同。
参数不同:
1)、如果参数的个数相同,那么参数的类型就不能相同。
2)、如果参数的类型相同,那么参数的个数就不能相同。

方法的重载跟返回值没有关系。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace _03方法的重载
{
    class Program
    {
        static void Main(string[] args)
        {
           // Console.WriteLine()
           // M()
        }


        public static void M(int n1, int n2)
        {
            int sum = n1 + n2;
        }

        //public static int M(int n1, int n2)
        //{ 
            
        //}
        public static double M(int n1, double n2)
        {
            return n1 + n2;
        }
        public static string M(string s1, string s2)
        {
            return s1 + s2;
        }
        public static void M(int n1, int n2, int n3)
        {
            int sum = n1 + n2 + n3;
        }


    }
}

可变参数数组

6、params可变参数:将实参列表中跟可变参数数组类型一样的参数当做是可变参数数组中的元素。
可变参数必须形参列表中的最后一个元素

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace _04可变参数数组
{
    class Program
    {
        static void Main(string[] args)
        {
            //求任意数字中的总和
            // int[] s={98,79,65};
            //GetScore("张三", 98, 79, 65,100,100);
            //Console.ReadKey();
       //     int[] n={1,2,3,4,5};
            int sum = GetSum(1.5,2,3,4,5,6);
            Console.Write(sum);
            Console.ReadKey();
        }

        public static int GetSum(double d,params int[] nums)
        {
            int sum = 0;
            for (int i = 0; i < nums.Length; i++)
            {
                sum += nums[i];
            }
            return sum;
        }


        public static void GetScore(string name,int id ,params int[] score)
        {
            int sum = 0;
            for (int i = 0; i < score.Length; i++)
            {
                sum += score[i];
            }

            Console.WriteLine("{0}这次考试的总成绩是{1}", name, sum);
        }

    }
}

递归

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace _05递归
{
    class Program
    {
        static void Main(string[] args)
        {
            //方法的递归  在方法内部自己调用自己
            //找一个文件夹下所有的文件
            TellStory();
            Console.ReadKey();
        }
        public static int i = 0;
        public static void TellStory()
        {
            i++;
            Console.WriteLine("从前有座山");
            Console.WriteLine("山里有个庙");
            Console.WriteLine("庙里有个小和尚和老和尚");
            Console.WriteLine("有一天,小和尚哭了,老和尚给小和尚讲了一个故事");
            if (i >= 5)
            {
                return;
            }
            TellStory();
        }
    }
}

方法的3个练习

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace _07方法的3个练习
{
    class Program
    {
        static void Main(string[] args)
        {
            //用方法来实现:有一个字符串数组:{ "马龙", "迈克尔乔丹", "雷吉米勒", "蒂姆邓肯", "科比布莱恩特" },请输出最长的字符串。
            //string[] names = { "马龙", "迈克尔乔丹", "雷吉米勒", "蒂姆邓肯", "科比布莱恩特" };
            //string max = GetLongest(names);
            //Console.WriteLine(max);
            //Console.ReadKey();
        
          //  81、写一个方法,用来判断用户输入的数字是不是质数  再写一个方法 要求用户只能输入数字 输入有误就一直让用户输入数字
            Console.WriteLine("请输入一个数字");
            int number = Convert.ToInt32(Console.ReadLine());
            //只能被1和自身整除的数字叫质数
            bool b = IsPrime(number);
            Console.WriteLine(b);
            Console.ReadKey();

        }

        public static bool IsPrime(int number)
        {
            if (number < 2)
            {
                return false;
            }
            else//>=2
            {
                for (int i = 2; i < number; i++)
                {
                    if (number % i == 0)
                    {
                        return false;
                    }
                }
                return true;
            }
        }


        public static string GetLongest(string[] names)
        {
            string max = names[0];
            for (int i = 0; i < names.Length; i++)
            {
                if (names[i].Length > max.Length)
                {
                    max = names[i];
                }
            }
            return max;
        }
    }
}

方法的6个练习

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace _08方法的6个练习
{
    class Program
    {
        static void Main(string[] args)
        {

            //95、接受输入后判断其等级并显示出来。判断依据如下:等级={优 (90~100分);良 (80~89分)
            //;中 (60~69分);差 (0~59分);}
            //Console.WriteLine("请输入学员考试成绩");
            //int score = Convert.ToInt32(Console.ReadLine());
            //string level = GetLevel(score);
            //Console.WriteLine(level);
            //Console.ReadKey();

            //97、请将字符串数组{ "中国", "美国", "巴西", "澳大利亚", "加拿大" }中的内容反转


            //如果写一个方法要对数组进行改变,这个方法不需要返回值,外面的数组也会随之而改变。
            //string[] names = { "中国", "美国", "巴西", "澳大利亚", "加拿大" };
            //Change(names);
            //for (int i = 0; i < names.Length; i++)
            //{
            //    Console.WriteLine(names[i]);
            //}
            //Console.ReadKey();


            //98写一个方法 计算圆的面积和周长  面积是 pI*R*R  周长是 2*Pi*r
            //double area;
            //double perimeter;
            //GetAreaPerimeter(5, out area, out perimeter);
            //Console.WriteLine(area);
            //Console.WriteLine(perimeter);
            //Console.ReadKey();


            //100、计算任意多个数间的最大值(提示:params)。
            //int max = GetMax(4, 5, 6, 7, 8, 9);
            //Console.WriteLine(max);
            //Console.ReadKey();


            //101、请通过冒泡排序法对整数数组{ 1, 3, 5, 7, 90, 2, 4, 6, 8, 10 }实现升序排序。
            //int[] nums = { 1, 3, 5, 7, 90, 2, 4, 6, 8, 10 };
            //MaoPao(nums);
            //for (int i = 0; i < nums.Length; i++)
            //{
            //    Console.WriteLine(nums[i]);
            //}
            //Console.ReadKey();



            //用方法来实现:请计算出一个整型数组的平均值。
            //{ 1, 3, 5, 7, 93, 33, 4, 4, 6, 8, 10 }。
            //要求:计算结果如果有小数,则显示小数点后两位(四舍五入)。
            //int[] nums = { 1, 3, 5, 7, 93, 33, 4, 4, 6, 8, 10 };
            //double avg = GetAvg(nums);
            //avg = Convert.ToDouble(avg.ToString("0.00"));
            //Console.WriteLine(avg);

            ////Console.WriteLine("{0:0.00}",avg);
            ////Console.WriteLine(avg);
            //Console.ReadKey();


            //102将一个字符串数组输出为|分割的形式,比如“梅西|卡卡|郑大世”(用方法来实现此功能)
            string[] names = { "梅西", "卡卡", "郑大世", "金秀贤", "金贤秀" };
            string str = ProcessString(names);
            Console.WriteLine(str);
            Console.ReadKey();
        }


        public static string ProcessString(string[] names)
        {
            string str = "";
            for (int i = 0; i < names.Length-1; i++)
            {
                str += names[i] + "|";
            }
            return str + names[names.Length - 1];
        }

        public static double GetAvg(int[] nums)
        {
            double sum = 0;
            for (int i = 0; i < nums.Length; i++)
            {
                sum += nums[i];
            }
            return sum / nums.Length;
        }


        public static void MaoPao(int[] nums)
        {
            for (int i = 0; i < nums.Length - 1; i++)
            {
                for (int j = 0; j < nums.Length - 1 - i; j++)
                {
                    if (nums[j] > nums[j + 1])
                    {
                        int temp = nums[j];
                        nums[j] = nums[j + 1];
                        nums[j + 1] = temp;
                    }
                }
            }
        }


        public static int GetMax(params int[] nums)
        {
            int max = nums[0];
            for (int i = 0; i < nums.Length; i++)
            {
                if (nums[i] > max)
                {
                    max = nums[i];
                }
            }
            return max;
        }



        public static void GetAreaPerimeter(double r, out double area, out double perimeter)
        {
            area = 3.14 * r * r;
            perimeter = 2 * 3.14 * r;
        }

        public static void Change(string[] names)
        {
            for (int i = 0; i < names.Length / 2; i++)
            {
                string temp = names[i];
                names[i] = names[names.Length - 1 - i];
                names[names.Length - 1 - i] = temp;
            }
        }

        public static string GetLevel(int score)
        {
            string level = "";
            switch (score / 10)
            {
                case 10:
                case 9: level = "优";
                    break;
                case 8: level = "良";
                    break;
                case 7: level = "中";
                    break;
                case 6: level = "差";
                    break;
                default: level = "不及格";
                    break;
            }
            return level;
        }
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值