码迷,mamicode.com
首页 > 其他好文 > 详细

C# 使用ref和out关键字

时间:2014-05-09 16:03:03      阅读:333      评论:0      收藏:0      [点我收藏+]

标签:style   blog   class   code   java   ext   

使用ref关键字,可以使参数按引用传递。当控制权传递回调用方法时,在方法中对参数的任何更改都将反映在该变量中。
若要使用ref关键字进行参数传递,则方法定义和调用方法都必须显示地使用ref关键字,而且使用ref关键字传递的参数必须最先进行初始化。
使用out关键字的方法与使用ref关键字的方法类似,同样会导致参数通过引用来传递。不同之处在于,使用out关键字传递的参数并不需要最先进行初始化,但需要在方法返回之前进行赋值。
若要使用out关键字传递参数,方法定义和调用方法都必须显示地使用out关键字。

bubuko.com,布布扣
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication1
{
    class Program
    {
        static void refMethod(ref string s)
        {
            s = "wangyuanfeng";
        }

        static void outMethod(out int i,out string str1,out string str2)
        {
            i = 44;
            str1 = "I‘ve been returned";
            str2 = null;
        }
                
        static void Main(string[] args)
        {
            string str = "old";
            int value = new int();
            string str1 = "old1";
            string str2 = "old2";
            
            Console.WriteLine("use ref:");
            Console.WriteLine("refMethod()before:\n str = {0}", str);
            refMethod(ref str);
            Console.WriteLine("refMethod() after :\n str = {0}", str);
            
            Console.WriteLine("use out:");
            Console.WriteLine("outMethod() before:\n nvalue = {0};nstr1 = {1},nstr2 = {2}", value, str1, str2);
            outMethod(out value, out str1, out str2);
            Console.WriteLine("outMethod() after:\n nvalue = {0},nstr1 = {1},nstr2 = {2}", value, str1, str2);

            Console.Read();
        }
    }
}
bubuko.com,布布扣

bubuko.com,布布扣

原文链接:http://www.douban.com/note/273675561/

C# 使用ref和out关键字,布布扣,bubuko.com

C# 使用ref和out关键字

标签:style   blog   class   code   java   ext   

原文地址:http://www.cnblogs.com/iwenr/p/3718166.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!