先看一下示例 using System; using System.Text; using System.Collections.Generic;
namespace Example_5 { class Program1 { ///<summary> ///比较a和b的大小并按由小到大的顺序排列a和b ///</summary> ///<param name="a">整数a</param> ///<param name="b">整数b</param> static void Swap(int a, int b) { int c = 0; if (a > b) { c = a; a = b; b = c; } }
static void Main (String[] args) { int x = 6; int y = 4; Swap(x,y); Console.WriteLine("x 的值为:{0},y的值为:{1}", x, y); Console.ReadLine(); } } } 我们的本意是比较a和b的大小并按由小到大的顺序排列a和b,可是结果是 x 的值为:6,y的值为:4 并没有像我们所想的哪样,输出我们想要的结果. 分析 实际上,这是由于C#中这一类型的调用默认为值参数的调用。既在使用参数时,将参数的值传给方法使用,而方法中对此值的改变并不影响方法的外部变量.所以没有得到我们想要的结果. 解决问题的方法是使用ref关键字. ref关键字是使用参数按引用来传递的.其效果是方法中对参数所做的任何改变将功反映到变量中. 改进的程序 using System; using System.Text; using System.Collections.Generic;
namespace Example_5 { class Program1 { ///<summary> ///比较a和b的大小并按由小到大的顺序排列a和b ///</summary> ///<param name="a">整数a</param> ///<param name="b">整数b</param> static void Swap(ref int a,ref int b) { int c = 0; if (a > b) { c = a; a = b; b = c; } }
static void Main (String[] args) { int x = 6; int y = 4; Swap(ref x,ref y); Console.WriteLine("x 的值为:{0},y的值为:{1}", x, y); Console.ReadLine(); } } } 运行结果为
说明 1.ref 关键字使参数按引用传递。 2.其效果是,当控制权传递回调用方法时,在方法中对参数所做的任何更改都将反映在该变量中。 3.使用ref 参数,方法定义和调用方法都必须显式使用 ref 关键字 4.传递到 ref 参数的参数必须最先初始化。 5. 示例代码 using System; using System.Text; using System.Collections.Generic;
namespace Example_5 { class Program1 { static void ChangeName(ref String ChangedName) { ChangedName = "宋井华"; }
static void Main () { String OrginalName = "sampsong"; ChangeName(ref OrginalName); Console.WriteLine(OrginalName); } } }
运行结果为: 宋井华 x 的值为:4,y的值为:6 |
[转]浅谈C#当中的ref关键字
最新推荐文章于 2024-02-06 08:30:00 发布
2007/04/25 11:37