博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
C#关于ref的用法(多个实参值的传递)
阅读量:7005 次
发布时间:2019-06-27

本文共 1654 字,大约阅读时间需要 5 分钟。

按照C#默认的按值调用参数的传递机制,不能刻编写出一个方法来实现两个int类型的值交换,因为一个方法只能对应一个返回值,如何实现将两个交换的值传递回去,这里我将用到的是ref修饰符。

使用ref的单值传递(没有返回值,但是直接将实参的值做了修改,如果是两个int型做值交换,ref也将直接对其实参进行修改为值交换后的值)

ps:这里说的有些不对,但是大体思路是这个样子,看例子自己领悟吧。就是在方法中直接对原本传进来的值进行修改。不需要return

using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.IO;namespace cxx{    class RefTest    {        public void  sqr( ref int i)   //注意ref实在所有参数类型的最前面        {             i = i * i;        }    }    class refDemo    {        static void Main()        {            RefTest ob = new RefTest();            int a = 10;            Console.WriteLine("a before call:" + a);            ob.sqr(ref a);  //还是在最前面            Console.WriteLine("a after call:" +a);            Console.WriteLine(@"my name is shonewornmy blog: www.cnblogs.com/shoneworn welcome to my blog !"); //对自己的博客做一下推广,同时也复习一下            Console.ReadKey();        }    }}

 

常规单值传递(不适用ref):

using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.IO;namespace cxx{    class RefTest    {        public int sqr( int i)        {            return i = i * i;  //注意方法类型为int型,需要用到return来返回值        }    }    class refDemo    {        static void Main()        {            RefTest ob = new RefTest();            int a = 10;            Console.WriteLine("a before call:" + a);           int b = ob.sqr( a);  //用b来接收值            Console.WriteLine("a after call:" + b);            Console.WriteLine(@"my name is shonewornmy blog: www.cnblogs.com/shoneworn welcome to my blog !");   //对自己的博客做一下推广,同时也复习一下            Console.ReadKey();        }    }}

 

转载于:https://www.cnblogs.com/shoneworn/p/3387387.html

你可能感兴趣的文章
js 事件模型
查看>>
Ubuntu 16.04 不能用inittab 设置 运行等级 runlevel
查看>>
asp.net源码坊2015-3月第二周TOP10下载排行
查看>>
看啦这么就别人的博客 我也来写一篇! Object转换其他类型
查看>>
UICollectionView官方使用示例代码研究
查看>>
Set接口
查看>>
disconf
查看>>
java类库 collection与collections (转)
查看>>
关于在微信支付接口和支付宝接口中使用到的辅助函数
查看>>
学习网页编程(一)
查看>>
Windows Server 2008 安装好之后的简单配置
查看>>
MyCat原理及分布式分库分表
查看>>
redis基础_redis介绍
查看>>
WPF中。。DataGrid 实现时间控件和下拉框控件
查看>>
几种常用排序
查看>>
oracle win7下 卸载
查看>>
JS两个相同的字符串被判断为不相等问题
查看>>
Python中的一些函数
查看>>
[leetcode-513-Find Bottom Left Tree Value]
查看>>
plt画空心饼图
查看>>