zoukankan      html  css  js  c++  java
  • C#关于ref的用法(多个实参值的传递)

    按照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 shoneworn
    my 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 shoneworn
    my blog: www.cnblogs.com/shoneworn 
    welcome to my blog !");   //对自己的博客做一下推广,同时也复习一下“@”的用法
    
    
                Console.ReadKey();
    
            }
        }
    }

  • 相关阅读:
    解决 idea 项目中Error:java: 无效的标记: XX:MaxPermSize=512M
    vant预览图片
    react路由
    computed和watch
    仓库系统面单常用的打印插件
    04.简单了解一下Redis企业级数据备份方案
    CRMEB 源码 login页 获取信息 缓存修改
    frp 搭建远程桌面
    ABP asp.net core 项目发布 IIS部署
    MYSQL 监控数据库SQL语句 查看数据库执行语句
  • 原文地址:https://www.cnblogs.com/shoneworn/p/3387387.html
Copyright © 2011-2022 走看看