你好,欢迎来到电脑编程技巧与维护杂志社! 杂志社简介广告服务读者反馈编程社区  
合订本订阅
 
 
您的位置:技术专栏 / Linux开发
正确理解C#中的ref关键字(1)
 
最近有人问到 ref 关键字的正确用法,下面我们来举例说明。其实要更好的理解 ref 关键字,结合 C++ 代码更加容易一些。另外在开始我们的例子之前,需要提前说明几点:

  C# 中的数据有两种类型:引用类型(reference types)和值类型(value types)。 简单类型(包括int, long, double等)和结构(structs)都是值类型,而其他的类都是引用类型。 简单类型在传值的时候会做复制操作,而引用类型只是传递引用,就像 C++ 中的指针一样。

  注意 structs 在 C# 和 C++ 中的区别。在 C++ 中, structs 和类基本相同(except that the default inheritance and default access are public rather than private)。 而在 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);
 }
}

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

(编辑:aniston)

  推荐精品文章

·2024年12月目录 
·2024年11月目录 
·2024年10月目录 
·2024年9月目录 
·2024年8月目录 
·2024年7月目录 
·2024年6月目录 
·2024年5月目录 
·2024年4月目录 
·2024年3月目录 
·2024年2月目录 
·2024年1月目录
·2023年12月目录
·2023年11月目录

  联系方式
TEL:010-82561037
Fax: 010-82561614
QQ: 100164630
Mail:gaojian@comprg.com.cn

  友情链接
 
Copyright 2001-2010, www.comprg.com.cn, All Rights Reserved
京ICP备14022230号-1,电话/传真:010-82561037 82561614 ,Mail:gaojian@comprg.com.cn
地址:北京市海淀区远大路20号宝蓝大厦E座704,邮编:100089