• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
一蓑烟雨
C/C++,Linux,语音技术
博客园    首页    新随笔    联系   管理    订阅  订阅
ref和out

 1、引用类型(ref、out)与值类型

引用类型都是引用传递(两者都是按地址传递的),就是对传递进去的变量的修改会反映在原来的变量上; 
值类型当不用 out或者 ref的时候就是值传递,就是对传递进去的变量的修改不会反映在原来的变量上,修改的只是原来变量的一个副本。

2、重载

ref 和 out 关键字在运行时的处理方式不同,但在编译时的处理方式相同。因此,如果一个方法采用 ref 参数,而另一个方法采用 out 参数,则无法重载这两个方法;

如果一个方法采用 ref 或 out 参数,而另一个方法不采用这两类参数,则可以进行重载。

3、初始化

ref 先初始化;
out 在方法里初始化。

4、ref 有进有出,out 只出不进

 以下输出结果 :i = 9

                   ref j =  36

                   q1 = 100

           out   q2 = 103 

refout.cs
 1 using System;
2 using System.Collections.Generic;
3 using System.Linq;
4 using System.Text;
5
6 namespace refout
7 {
8 class Program
9 {
10 static void fun(int m)
11 {
12 int k = 4;
13 m = k * m;
14 }
15 static void fun(ref int m)//可重载
16 {
17 int g = 4;
18 m = g * m;
19 }
20 static void func(int q)
21 {
22 q += 3;
23 }
24 static void func(out int q)
25 {
26 q = 100;
27 q += 3;
28 }
29 static void Main(string[] args)
30 {
31 //引用传递
32 int i=9,j=9;
33 int q1=100,q2;
34 fun(i);
35 Console.WriteLine("ref i ={0}",i);
36 //值传递
37 fun(ref j);
38 Console.WriteLine("j = {0}",j);
39 func(q1);
40 Console.WriteLine("q1 = {0}",q1);
41 func(out q2);
42 Console.WriteLine("out q2 = {0}",q2);
43 }
44 }
45 }
posted on 2011-12-05 10:30  lovemu  阅读(296)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3