zoukankan      html  css  js  c++  java
  • C#高级参数ref的使用

    ref关键字用于将方法内的变量改变后带出方法外。具体我们通过例子来说明:

    例子中,将变量n1和n2交换了。如果没有加ref参数,由于没有swadDemo()方法没有返回值,调用后,n1和n2是不会交换的,但是加了ref后,变量便会在swadDemo()中改变后并带出。

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    
    namespace blog
    {
        class Program
        {
            static void Main(string[] args)
            {
    
                refDemo();
            }
            #region 使用高级参数ref
            private static void refDemo()
            {
                int n1 = 1;
                int n2 = 2;
                swadDemo(ref n1, ref n2);
                Console.WriteLine("n1:" + n1 + "
    " + "n2:" + n2);
                Console.ReadLine();
            }
            #endregion
    
            #region 高级参数ref用法
            public static void swadDemo(ref int a, ref int b)
            {
    
                //注意,这个方法中,并没有返回值。但是,由于加了ref,
                //所以会将变量改变后再带出。
                //ref参数,用于将方法内的变量改变后带出方法外
                int temp;
                temp = a;
                a = b;
                b = temp;
            }
            #endregion
        }
    }
  • 相关阅读:
    USACO 3.3 A Game
    USACO 3.3 Camelot
    USACO 3.3 Shopping Offers
    USACO 3.3 TEXT Eulerian Tour中的Cows on Parade一点理解
    USACO 3.3 Riding the Fences
    USACO 3.2 Magic Squares
    USACO 3.2 Stringsobits
    USACO 3.2 Factorials
    USACO 3.2 Contact
    USACO 3.1 Humble Numbers
  • 原文地址:https://www.cnblogs.com/linfenghp/p/6619135.html
Copyright © 2011-2022 走看看