out关键字和ref案例

来源:互联网 发布:公文写作神器软件 编辑:程序博客网 时间:2024/06/08 07:33

out关键字

using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks;namespace out关键字{    class Program    {        static void Main(string[] args)        {            Console.WriteLine("请输入一个整数");            int result;            bool ret = MyTryParse(Console.ReadLine(),out result);            if (ret)            {                Console.WriteLine(result);            }            else            {                Console.WriteLine("您的输入不合法"+result);            }            int numbers = 46;            int arr;            int day;            Test(46, out arr, out day);            Console.WriteLine("{0}周{1}天",arr,day);        }        static void Test(int days,out int week,out int day)        {            week = 0;            day = 0;            week = days / 7;            day = days % 7;        }        static bool MyTryParse(string str,out int result)        {            result = 0;            for (int i = 0; i < str.Length; i++)            {                //如果发现有一个字符不在str[i]>='0' && str[i]<='9'区间范围内  那么就证明这不是一个纯数字的字符串                if ( !(str[i]>='0' && str[i]<='9'))                {                    return false;                }            }            //作用是给result赋值并打印            result = int.Parse(str);            //作用是返回            return true;        }    }}

ref案例

using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks;namespace ref案例{    class Program    {        static void Main(string[] args)        {            //int num1 = 10;            //int num2 = 20;            //Swap(ref num1,ref num2);            //Console.WriteLine("+++ num1={0},num2={1}",num1,num2);            int[] numArr1 = { 1, 2, 3, 4, 5, 6 };            int[] numArr2 = { 9, 8, 7, 6, 5, 4 ,3};            Swap(ref numArr1,ref numArr2);            PrintArr(numArr1);            PrintArr(numArr2);        }        //交换两个数字        //reference        static void Swap(ref int num1,ref int num2)        {            int temp = num1;            num1 = num2;            num2 = temp;            Console.WriteLine("**** num1={0},num2={1}",num1,num2 );        }        static void Swap(ref int[] arr1,ref int[] arr2)        {            int[] tempArr = arr1;            arr1 = arr2;            arr2 = tempArr;        }        static void PrintArr(int[] arr)        {            for (int i = 0; i < arr.Length; i++)            {                Console.Write(arr[i]+" ");            }            Console.WriteLine();        }    }}
原创粉丝点击