ref & out - C#中的参数传递
【ref & out - C#中的参数传递】
ref与out均指定函数参数按引用传递,惟一的不同是,ref传递的参数必须初始化,而out可以不用。
ref与out无法作为重载的依据,即ref与out编译器认为一样。如下:
但是ref函数与非ref函数是可以重载的,如下:
To use a ref parameter, both the method definition and the calling method must explicitly use the ref keyword, as shown in the following example.
A variable of a reference type does not contain its data directly; it contains a reference to its data. When you pass a reference-type parameter by value, it is possible to change the data pointed to by the reference, such as the value of a class member. However, you cannot change the value of the reference itself; that is, you cannot use the same reference to allocate memory for a new class and have it persist outside the block. To do that, pass the parameter using the ref or out keyword.
class PassingRefByVal
{
static void Change(int[] pArray)
{
pArray[] = ; // This change affects the original element.
pArray = new int[] {-, -, -, -, -}; // This change is local.
System.Console.WriteLine("Inside the method, the first element is: {0}", pArray[]);
} static void Main()
{
int[] arr = {, , };
System.Console.WriteLine("Inside Main, before calling the method, the first element is: {0}", arr []); Change(arr);
System.Console.WriteLine("Inside Main, after calling the method, the first element is: {0}", arr []);
}
}
/* Output:
Inside Main, before calling the method, the first element is: 1
Inside the method, the first element is: -3
Inside Main, after calling the method, the first element is: 888
*/
参考:
1、http://msdn.microsoft.com/zh-cn/library/14akc2c7(VS.80).aspx
2、http://msdn.microsoft.com/zh-cn/library/t3c3bfhx(v=vs.80).aspx
3、http://msdn.microsoft.com/zh-cn/library/s6938f28.aspx
最新文章
- extjs combobox
- 第55讲:Scala中Infix Type实战详解
- 简单CSS布局留用
- 深入了解ios系统机制
- [IOS UIalert模版]
- VS2012 中使用Emacs布局
- java求阶乘
- SVN报Previous operation has not finished; run 'cleanup'&
- Dynamics 365 for CRM: Sitemap站点图的可视化编辑功能
- MySql-两阶段加锁协议
- 基本DFS与BFS算法(C++实现)
- [CodeChef-CAPTCITI]Snakes capturing the Mongoose Cities
- IO流的总结(二)
- SpringBoot 试手(简易的SpringBoot搭建步骤)
- mysql 数据表备份导出,恢复导入操作实践
- C#--readlyonly关键字
- PKU OJ 1002 487-3279
- XE7 update1
- Win10内部更新:警告用户别用chrome和Firefox
- UVa 11178:Morley’s Theorem(两射线交点)