以C#为例:其值类型为sbyte,byte,char,short,ushort,int,uint,long和ulong,float和double,当然还有decimal和bool。而引用类型则是string和object。
我想说的
我想说的就是——Ref和Out把我弄糊涂的原因是,当时没有认真的去分析它对不同类型所做出的不同的动作。
对于值类型。
使用了Ref和Out的效果就几乎和C中使用了指针变量一样。它能够让你直接对原数进行操作,而不是对那个原数的Copy进行操作。举个小例子:
using System;namespace ConsoleApplication4 { /// <summary> /// Class1 的摘要说明。 /// </summary> class Class1 { /// <summary> /// 应用程序的主入口点。 /// </summary> [STAThread] static void Main(string[] args) { int a = 5; int b; squareRef(ref a); squareOut(out b); Console.WriteLine("The a in the Main is: " + a); Console.WriteLine("The b in the Main is: " + b); } static void squareRef(ref int x) { x = x * x; Console.WriteLine("The x in the squareRef is: " + x); } static void squareOut(out int y) { y = 10; y = y * y; Console.WriteLine("The y in the squareOut is: " + y); } } }
显示的结果就是——25 100 25 100。
这样的话,就达到了和C中的指针变量一样的作用。
对于引用类型。
对于引用类型就比较难理解了。
先要了解到这一层——就是当一个方法接收到一个引用类型的变量的时候,它将获得这个引用(Reference)的一个Copy。由于Ref关键字可以用来向方法传递引用。所以,如果这个功能被误用了——比如:当一个如数组类型的引用对象用关键字Ref传递的时候,被调用的方法实际上已经控制了传递过来的引用本身。这样将使得被调用方法能用不同的对象甚至NULL来代替调用者的原始引用!

如图。内存地址为2000的变量arrayA中其实存放着数组{1,2,3,4,……}的内存起始地址10000。如果一个方法fun()使用fun( arrayA[] )的话,它将顺利的获得数据10000,但这个10000将放在一个Copy中,不会放到内存的2000位置。而这个时候我们如果使用fun( ref arrayA[] )的话,我们得到的值就是2000啦(也就是说,被调用方法能够修改掉arrayA中的那个引用,使之不再指向10000,甚至可以用NULL来代替10000,这样的话,那个10000地址中的数据可能就要被垃圾回收机制清理了。)
有个例子:
using System; using System.Drawing; using System.Collections; using System.ComponentModel; using System.Windows.Forms; using System.Data;
namespace RefOut { /// <summary> /// Form1 的摘要说明。 /// </summary> public class Form1 : System.Windows.Forms.Form { private System.Windows.Forms.Button button1; private System.Windows.Forms.Label label1; /// <summary> /// 必需的设计器变量。 /// </summary> private System.ComponentModel.Container components = null;
public Form1() { // // Windows 窗体设计器支持所必需的 // InitializeComponent();
// // TODO: 在 InitializeComponent 调用后添加任何构造函数代码 // }
/// <summary> /// 清理所有正在使用的资源。 /// </summary> protected override void Dispose( bool disposing ) { if( disposing ) { if (components != null) { components.Dispose(); } } base.Dispose( disposing ); }
#region Windows 窗体设计器生成的代码 /// <summary> /// 设计器支持所需的方法 - 不要使用代码编辑器修改 /// 此方法的内容。 /// </summary> private void InitializeComponent() { this.button1 = new System.Windows.Forms.Button(); this.label1 = new System.Windows.Forms.Label(); this.SuspendLayout(); // // button1 // this.button1.Dock = System.Windows.Forms.DockStyle.Top; this.button1.Location = new System.Drawing.Point(0, 0); this.button1.Name = "button1"; this.button1.Size = new System.Drawing.Size(480, 32);
(编辑:焦作站长网)
【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!
|