zoukankan      html  css  js  c++  java
  • 函数的ref 和out 参数

    Ref参数:

    class Program

        {

            static void Main(string[] args)

            {

                int a = 10;

                Swap(a);//正常的调用是值传递,相当于把a的值复制到Swap中

                Console.WriteLine("在调用Swap后a={0}",a);//所以调用完Swap后,a的值仍然是10

                Change(ref a);//ref是引用,是调用后直接把a的值给改变了。

                Console.WriteLine("在调用Change后a={0}", a);//所以调用完Change后,a的值变成了15,和Change里面的a一样了

                Console.ReadKey();

            }

            static void Swap(int a)

            {

                a  = a  + 5;

                Console.WriteLine(a );//在Swap中a的值增加了5,变成了15

            }

            static void Change(ref int a)

            {

                a = a + 5;

                Console.WriteLine(a);

            }

        }

     

    Out参数:

    class Program

        {

            static void Main(string[] args)

            {

                int a;//当要用到out参数的时候,定义的变量不能赋值,要留给out赋值

                Swap(out a);//调用Swap

                Console.WriteLine(a);

                Console.ReadKey();

            }

            static void Swap(out int a)//Swap中参数out 的作用是给a赋初值

            {

                a = 10;

                Console.WriteLine(a );//在Swap中a的值增加了5,变成了15

            }

        }

     

    class Program

        {

            static void Main(string[] args)

            {

                string s = Console.ReadLine();

                int i;

                if (int.TryParse(s, out i))//调用int的TryParse属性,如果输入的s能转换为int类型,则为true,否则为false

                {

                   i=i+10;

                    Console.WriteLine ("i={0}",i );

                }

                else

                {

                    Console.WriteLine ("输入格式错误");

                }

                Console.ReadKey();

            }

        }

    PS:ref和out的区别:ref是对已经赋值的变量对其的值进行改变,而out是对未赋值的变量进行初始化

  • 相关阅读:
    网络请求侦听工具
    再转动画实现
    转如何解决EXC_BAD_ACCESS错误
    关于Iphone开发得一些案例及常用知识(转过来的参考用)
    用uiwebview打开pdf,word,excel
    转 iphone开发资料汇总(很多实用的东东)
    设置uiview背景图的方法之一
    给状态条加上图标的代码
    xcode 4 下找EXC_BAD_ACCESS错误原因
    linux&unix常用命令
  • 原文地址:https://www.cnblogs.com/ruishuang208/p/3072628.html
Copyright © 2011-2022 走看看