>  기사  >  백엔드 개발  >  C#의 세 가지 키워드 params, Ref 및 out에 대한 자세한 소개

C#의 세 가지 키워드 params, Ref 및 out에 대한 자세한 소개

黄舟
黄舟원래의
2017-05-28 10:09:201709검색

이 글에서는 주로 params 키워드, ref 키워드, out 키워드에 대해 설명합니다. 매우 좋습니다. 참조 값이 있으며, 필요한 친구가 참조할 수 있습니다

이 세 가지 키워드에 대한 원래 작업 중 일부를 연구하기 전에

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

실행 결과를 관찰하고

값이 변경되지 않았는지 확인하세요. , 즉 이때의 연산 원리는 이전의 C 언어에서의 함수 연산과 동일할 수 있습니다.

이번 글에서는 주로 params 키워드, ref 키워드, out 키워드에 대해 논의합니다.

 1) params 키워드, 공식적인 설명은 메소드 매개변수의 길이가 가변적일 때 사용된다는 것입니다. 때로는 메소드에 얼마나 많은 메소드 매개변수가 있는지 확실하지 않을 경우 params 키워드를 사용하여 문제를 해결할 수 있습니다.


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 키워드:

를 사용하여 type 매개변수를 참조합니다. 메서드의 매개변수에 대한 모든 변경 사항은 variable


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 키워드에 반영됩니다. 참조하지만 초기화할 필요는 없습니다.

위 내용은 C#의 세 가지 키워드 params, Ref 및 out에 대한 자세한 소개의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.