A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© 孤神法法 中级黑马   /  2014-3-14 15:39  /  1500 人查看  /  1 人回复  /   1 人收藏 转载请遵从CC协议 禁止商业使用本文

方法中参数前如果不加任何修饰符,则参数按值传递,不会改变原有值的值,当加入out时候,参数作为输出参数,在方法中必须初始化该参数,并且是按地址传递,改变接受该参数的值,当用ref修饰时,参数则可以理解为既可以当做输出参数,也可以当做输入参数,那么响应的在方法体中可以对该参数初始化或者不初始化!下面举例说明
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace @ref
{
    class Program
    {
        static void Main(string[] args)
        {
            int number = 10;
            int result=Test(number);
            Console.WriteLine("number的值为:{0},result的值为:{1}",number,result);
            Console.ReadKey();
        }
       public static int Test(int a)
        {
            a = a+100;
            return a;
        }
    }
}
该参数按值传递,不会改变number的值,
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace @ref
{
    class Program
    {
        static void Main(string[] args)
        {
            int number = 10;
            int result=Test(out number);
            Console.WriteLine("number的值为:{0},result的值为:{1}",number,result);
            Console.ReadKey();
        }
       public static int Test(out int a)
        {
            a = 1;
            a = a+100;
            return a;
        }
    }
}
该参数是按地址传递,在方法体中必须初始化,number的值会改变!
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace @ref
{
    class Program
    {
        static void Main(string[] args)
        {
            int number=5;
            int result=Test(ref number);
            Console.WriteLine("number的值为:{0},result的值为:{1}",number,result);
            Console.ReadKey();
        }
       public static int Test(ref int a)
        {
            a = 13;//此处不省略则可以理解为输出参数,省略则可以理解为输入参数         
            a = a+100;
            return a;
        }
    }
}
ref修饰可以当做输入或者输出参数,

评分

参与人数 1技术分 +1 收起 理由
czwanglei + 1

查看全部评分

1 个回复

倒序浏览
值得学习ing!
回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马