C# 매개변수

WBOY
풀어 주다: 2024-09-03 15:19:00
원래의
184명이 탐색했습니다.

Params는 C#에서 매우 중요한 키워드입니다. 인수의 개수를 변수로 주고 싶을 때 param을 사용했습니다. 그래서 개발자가 사용될 매개변수의 개수를 모를 때 사용됩니다. C# Params 키워드 뒤에는 함수에 추가 매개변수가 허용되지 않습니다. 인수를 전달하지 않으면 params의 길이는 0으로 유지됩니다. 쉼표로 구분된 값이나 배열을 보낼 수 있습니다.

키워드: params

using System;
namespace Examples {
class Test {
// function containing params parameters
public static int Addittion(params int[] ListNumbers)
{
int total = 0;
// foreach loop
foreach(int i in ListNumbers)
{
total += i;
}
return total;
}
// Driver Code
static void Main(string[] args)
{
// Calling function by passing 5
// arguments as follows
int y = Addittion (12,13,10,15,56);
// Displaying result
Console.WriteLine(y);
}
}
}
로그인 후 복사

출력:

C# 매개변수

params 키워드 사용:

static public int add(params int[] args)
{
int add1 = 0;
foreach (var item in args)
add1= add1+item + 2;
return add1;
}
로그인 후 복사

매개변수 없음 키워드:

static public int add(int[] args)
{
int add = 0;
foreach (var item in args)
add1 = add1+item + 2;
return add1;
}
로그인 후 복사

param을 사용하면 add(1,4,5)와 같은 메소드를 호출할 수 있지만 param이 없으면 호출할 수 없습니다.

C# 매개변수의 예

다음 예는 C#에서 매개변수를 구현하는 방법을 보여줍니다.

예시 #1

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Params
{
class Demo
{
public void Show(params int[] num) // Params Paramater
{
for (int a = 0; a < num.Length; a++)
{
Console.WriteLine(num[a]);
}
}
static void Main(string[] args) // main function
{
Demo program = new Demo();  // Creating Object
program.Show(20, 4, 64, 3, 20, 2, 14);  // Passing arguments of variable length
Console.ReadLine();
}
}
}
로그인 후 복사

위의 예에서는 param 키워드가 사용되어 모든 유형과 개수의 유형을 허용합니다. 그런 다음 객체를 생성한 후 표시할 여러 인수를 전달합니다.

출력:

C# 매개변수

예시 #2

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Params
{
class Demo
{
public void Show(params object[] val) // Params Paramater
{
for (int a = 0; a < val.Length; a++)
{
Console.WriteLine(val[a]);
}
}
static void Main(string[] args) // main method
{
Demo program = new Demo(); // Creating Object
program.Show("Javascript", "Dotnet", 11, 10.50, "Param", 'h',"Example"); // Passing arguments of variable length
Console.ReadLine();
}
}
}
로그인 후 복사

위의 예에서는 param 키워드가 사용되어 모든 유형과 개수의 유형을 허용합니다. 객체를 생성한 후 표시할 여러 인수를 전달합니다. 여기에서 다양한 데이터 유형의 인수를 볼 수 있습니다.

출력:

C# 매개변수

예시 #3

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Params
{
class Demo
{
public static int Addition(params int[] num) // params parameter
{
int add = 0;
// foreach loop
foreach (int a in num)
{
add += a;
}
return add;
}
static void Main(string[] args)
{
int x = Addition(23, 45, 2, 36, 76);  // call function
// Displaying result
Console.WriteLine(x);
Console.ReadLine();
}
}
}
로그인 후 복사

위의 예에서는 배열이 사용되었으며, 인수의 유형과 수에 제한이 없는 param 키워드가 사용되었으므로 배열의 크기를 언급할 필요가 없습니다.  숫자는 다음 형식을 따릅니다.

[0] 25
[1] 45
[2]  2
[3]  36
[4]  76

출력:

C# 매개변수

예시 #4

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Params
{
class Demo
{
static void Main()
{
// Call params method with five integer type arguments
int cal1 = calParameters(7);
int cal2 = calParameters(11, 23);
int cal3 = calParameters(46, 8, 45);
int cal4 = calParameters(23, 31, 21, 45);
int cal5 = calParameters(12, 12, 54, 76);
// display result of each calculations
Console.WriteLine(cal1);
Console.WriteLine(cal2);
Console.WriteLine(cal3);
Console.WriteLine(cal4);
Console.WriteLine(cal5);
Console.ReadLine();
}
static int calParameters(params int[] values)
{
int sum = 0;
foreach (int value in values)    // foreach loop and sum of integers
{
sum += value;
}
return sum;
}
}
}
로그인 후 복사

위 예에서는 param 키워드가 사용되는 인수가 5개 있습니다. 모든 인수는 정수 유형입니다. foreach 루프는 각 인수의 합계를 표시하는 데 사용됩니다.

출력:

C# 매개변수

어레이와 어떻게 다릅니까?

public void test(params int[] args) { }
test(); // no compile-time error, args will be empty
로그인 후 복사

그러나 배열을 사용하는 경우:

public void test(int[] args) { }
test(); // error: No overload for 'Foo' takes 0 arguments
로그인 후 복사

따라서 인수를 전달하지 않으면 매개변수의 길이는 0으로 유지됩니다. Param 키워드는 매개변수 목록의 마지막에 있어야 합니다. 그렇지 않으면 오류가 발생합니다.

예:

public void test(params int[] args,int value) { }
로그인 후 복사

이런 선언은 허용되지 않습니다.

위 내용은 C# 매개변수의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

관련 라벨:
원천:php
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!