ref in C#


  最近有人问到 ref 关键字的正确用法,下面我们来举例说明。另外在开始我们的例子之前,需要提前说明几点:

  • C# 中的数据有两种类型:引用类型(reference types)和值类型(value types)。 简单类型(包括int, long, double等)和结构(structs)都是值类型,而其他的类都是引用类型。 简单类型在传值的时候会做复制操作,而引用类型只是传递引用,就像 C++ 中的指针一样。
  • 在 C# 中,structs 和类有很大的区别。其中最大的区别(我个人觉得,同时也是容易忽略的一个地方)可能就是它是值类型,而不是引用类型。

 

  下面这段代码是 MSDN 中的例子:

// cs_ref.cs
using System;
public class MyClass 
{
  public static void TestRef(ref char i) 
  {
    // The value of i will be changed in the calling method
    i = 'b';
  }
   
  public static void TestNoRef(char i) 
  {
    // The value of i will be unchanged in the calling method
    i = 'c';
  }
   
  // This method passes a variable as a ref parameter; the value of the 
  // variable is changed after control passes back to this method.
  // The same variable is passed as a value parameter; the value of the
  // variable is unchanged after control is passed back to this method.
  public static void Main() 
  { 
    char i = 'a';    // variable must be initialized
    TestRef(ref i);  // the arg must be passed as ref
    Console.WriteLine(i);
    TestNoRef(i);
    Console.WriteLine(i);
  }
}

  大家很容易看出输出结果是:

b
b

 


 那么如果把这个例子做一些新的改动,将值类型(这里用的是 char)改成引用类型,程序运行又是什么效果呢?

// ----------------------------------------
// MyClass definition
public class MyClass
{
  public int Value;
}
 
 
// ----------------------------------------
// Tester methods
public static void TestRef(ref MyClass m)
{
  m.Value = 10;
}
 
public static void TestNoRef(MyClass m)
{
  m.Value = 20;
}
 
public static void TestCreateRef(ref MyClass m)
{
  m = new MyClass();
  m.Value = 100;
}
 
public static void TestCreateNoRef(MyClass m)
{
  m = new MyClass();
  m.Value = 200;
}
 
public static void Main()
{
  MyClass m = new MyClass();
  m.Value = 1;
   
  TestRef(ref m);
  Console.WriteLine(m.Value);
   
  TestNoRef(m);
  Console.WriteLine(m.Value);
   
  TestCreateRef(ref m);
  Console.WriteLine(m.Value);
   
  TestCreateNoRef(m);
  Console.WriteLine(m.Value);
}

输出结果是:

10
20
100
100

From:http://www.csharpwin.com/csharpspace/43.shtml

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值