out参数的使用

1.out参数的使用

static void Main(string[] args)
        {
            //out 参数的使用
            int[] nums = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
            GetMaxMinSumAvg(nums,out int max,out int min,out int sum,out int avg, out bool b, out string s, out double d);
            Console.WriteLine("最大值是:{0},最小值是:{1},求和是:{2},平均值是:{3},布尔值是:{4},字符串是:{5},浮点数是:{6}", max, min, sum, avg,b,s,d);
        }

        public static void GetMaxMinSumAvg(int[] nums,out int max,out int min,out int sum,out int avg,out bool b,out string s,out double d)
        {
            
            max = nums[0];//max
            min = nums[0];//min
            sum = 0;//sum
            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;


            b = true;
            s = "123";
            d = 3.13;
        }

2.out参数做登录例子

static void Main(string[] args)
        {
            //登录的例子
            Console.WriteLine("请输入用户名:");
            string userName = Console.ReadLine();
            Console.WriteLine("请输入密码:");
            string userPwd = Console.ReadLine();
            bool b=IsLogin(userName,userPwd,out string msg);
            Console.WriteLine(b);
            Console.WriteLine(msg);
        }

        public static bool IsLogin(string userName,string userPwd,out string msg)
        {
            if (userName == "admin" && userPwd == "123")
            {
                msg = "登录成功";
                return true;
            }
            else if (userName == "admin")
            {
                msg = "密码错误";
                return false;
            }
            else if(userPwd == "123")
            {
                msg = "用户错误";
                return false;
            }
            else
            {
                msg = "用户名或密码错误";
                return false;
            }
        }

3.结合out参数所学自己实现一个TryParse

static void Main(string[] args)
        {
            string s = "123abc";
            int msg;
            bool b=MyTryParse(s, out msg);
            Console.WriteLine(msg);
            Console.WriteLine(b);
        }

        public static bool MyTryParse(string s,out int result )
        {
            result = 0;
            try
            {
                result = int.Parse(s);
                return true;
            }
            catch
            {
                return false;
            }
        }

 

3.总结

需要方法返回多个不通类型的值

out参数在方法体内必须赋值;

上一篇:JAVA---自定义异常


下一篇:验证反射机制的灵活性。