您所在的位置:开发 > .NET > 正确理解C#中的ref关键字(1)

正确理解C#中的ref关键字(1)

2007-08-29 16:46 Kellin 天极网 我要评论(0) 字号:T | T
一键收藏,随时查看,分享好友!

本文举例说明C#的ref关键字的正确用法,供大家参考!

AD:

最近有人问到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);
}
}

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

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);
}

内容导航

网友评论TOP5

查看所有评论(

提交评论

  1. 编程排行榜:图形编程的LOGO语言
  2. 什么是响应式Web设计?

热点专题

更多>>

读书

程序设计实践双语版
程序设计实践并不只是写代码。程序员必须评论各种折衷方案,在许多可能性之中做出选择、排除错误、做测试和改进程序性能,还要维

51CTO旗下网站

领先的IT技术网站 51CTO 领先的中文存储媒体 WatchStor 中国首个CIO网站 CIOage 中国首家数字医疗网站 HC3i 移动互联网生活门户 灵客风LinkPhone