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是对未赋值的变量进行初始化

  • 相关阅读:
    【UVa】And Then There Was One(dp)
    【vijos】1006 晴天小猪历险记之Hill(dijkstra)
    【UVa】Palindromic Subsequence(dp+字典序)
    【UVa】Wavio Sequence(dp)
    【UVa】Salesmen(dp)
    【UVa】Partitioning by Palindromes(dp)
    小结:特殊的技巧
    java 中 进程和线程的区别
    java中的 sleep() 和 wait() 有什么区别?
    Java 静态static 关键字作用
  • 原文地址:https://www.cnblogs.com/ruishuang208/p/3072628.html
Copyright © 2011-2022 走看看