雷火电竞-中国电竞赛事及体育赛事平台

歡迎來到入門教程網(wǎng)!

C#教程

當前位置:主頁 > 軟件編程 > C#教程 >

詳解C#中三個關(guān)鍵字params,Ref,out

來源:本站原創(chuàng)|時間:2020-01-10|欄目:C#教程|點擊:

關(guān)于這三個關(guān)鍵字之前可以研究一下原本的一些操作

using System;
using System.Collections.Generic;
using System.Text;
namespace ParamsRefOut
{
  class Program
  {
    static void ChangeValue(int i)
    {
      i=5;
      Console.WriteLine("The ChangeValue method changed the value "+i.ToString());
    }
    static void Main(string[] args)
    {
      int i = 10;
      Console.WriteLine("The value of I is "+i.ToString());
      ChangeValue(i);
      Console.WriteLine("The value of I is " + i.ToString());
      Console.ReadLine();
    }
  }
}

觀察運行結(jié)果發(fā)現(xiàn)

值并沒有被改變,也就是說此時的操作的原理可能也是跟以前C語言的函數(shù)操作是一樣的

本文主要討論params關(guān)鍵字,ref關(guān)鍵字,out關(guān)鍵字。

  1)params關(guān)鍵字,官方給出的解釋為用于方法參數(shù)長度不定的情況。有時候不能確定一個方法的方法參數(shù)到底有多少個,可以使用params關(guān)鍵字來解決問題。

using System;
using System.Collections.Generic;
using System.Text;
namespace ParamsRefOut
{
  class number
  {
    public static void UseParams(params int [] list)
    {
      for(int i=0;i<list.Length;i++)
      {
        Console.WriteLine(list[i]);
      }
    }
    static void Main(string[] args)
    {
      UseParams(1,2,3);
      int[] myArray = new int[3] {10,11,12};
      UseParams(myArray);
      Console.ReadLine();
    }
  }
}

  2)ref關(guān)鍵字:使用引用類型參數(shù),在方法中對參數(shù)所做的任何更改都將反應在該變量中

using System;
using System.Collections.Generic;
using System.Text;
namespace ParamsRefOut
{
  class number
  {
    static void Main()
    {
      int val = 0;
      Method(ref val);
      Console.WriteLine(val.ToString());
    }
    static void Method(ref int i)
    {
      i = 44;
    }
  }
}

  3) out 關(guān)鍵字:out 與ref相似但是out 無需進行初始化。

以上所述是小編給大家介紹的C#中三個關(guān)鍵字params,Ref,out,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復大家的。在此也非常感謝大家對我們網(wǎng)站的支持!

上一篇:C#將Word轉(zhuǎn)換成PDF方法匯總(基于Office和WPS)

欄    目:C#教程

下一篇:C#基于OLEDB獲取Excel文件表結(jié)構(gòu)信息的方法

本文標題:詳解C#中三個關(guān)鍵字params,Ref,out

本文地址:http://www.jygsgssxh.com/a1/C_jiaocheng/5721.html

網(wǎng)頁制作CMS教程網(wǎng)絡(luò)編程軟件編程腳本語言數(shù)據(jù)庫服務器

如果侵犯了您的權(quán)利,請與我們聯(lián)系,我們將在24小時內(nèi)進行處理、任何非本站因素導致的法律后果,本站均不負任何責任。

聯(lián)系QQ:835971066 | 郵箱:835971066#qq.com(#換成@)

Copyright © 2002-2020 腳本教程網(wǎng) 版權(quán)所有