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

  • 相关阅读:
    阻止a链接跳转的点击事件
    appium python版api
    Appium—python_ 安卓手机划屏幕操作
    appium-unittest框架中的断言
    Appium 服务关键字
    python mysql入库的时候字符转义
    python实现两个字典合并
    解决linux登录后总是时间过会就断开(解决ssh登录后闲置时间过长而断开连接)
    linux安装好redis,如何在window端访问?
    linux上安装redis
  • 原文地址:https://www.cnblogs.com/shoneworn/p/3387387.html
Copyright © 2011-2022 走看看