C#/수업 내용
c# out, ref, Int32.TryParse,TryParse(String, Int32) 과
Lewisjkim
2022. 1. 12. 16:39
ref=
참조 전달 방식으로
실제 데이터는 매개변수가 선언된 쪽에서만 저장하고,
호출된 메서드에서는 참조(가리키는것)만 하는 형태로
변수 이름만 전달하는 방식이다
- 메서드 시그니처 및 메서드 호출에서 인수를 메서드에 참조로 전달합니다.
- 메서드 시그니처에서 값을 호출자에게 참조로 반환합니다.
- 멤버 본문에서 참조 반환 값이 호출자가 수정하려는 참조로 로컬에 저장됨을 나타냅니다. 또는 지역 변수가 참조로 다른 값에 액세스함을 나타냅니다.
- struct 선언에서 ref struct 또는 readonly ref struct를 선언합니다.
방법=
static void Main(string[] args)
{
Vector v1;
v1.X = 5;
v1.Y = 10;
Change(ref v1);
Console.WriteLine(v1);
}
static void Change(ref Vector vt)
{
vt.X = 7;
vt.Y = 11;
}
출처: https://jeong-pro.tistory.com/53 [기본기를 쌓는 정아마추어 코딩블로그]
out=
반환형 전달 방식으로
메서드를 호출하는 쪽에서 선언만 하고,
초기화하지 않고 전달하면
메서드 쪽에서 해당 데이터를
초기화해서 넘겨주는 방식
using System;
class ABC
{
static void Main()
{
int num;//a 변수를 반드시 초기화할 필요 없음
Do(out num); //반환형 매개변수 전달 방식
Console.WriteLine($"[2]{num}");//1234
}
static void Do(out int num)
{
num =1234; //bref와 동일: 호출한 부분에 적용, 반드시 초기화해야 함
Console.WriteLine($"[1]{num}");//1234
}
}
-------------------
Int32.TryParse=
숫자의 문자열 표현을 해당하는 32비트 부호 있는 정수로 변환.
"11" => 11(32-bit 정수)
TryParse(String, Int32)=
정수)
Int32.TryParse(변환하고싶은 string type 숫자, Out (정수 type 매개변수)
using System;
public class Example
{
public static void Main()
{
String[] values = { null, "160519", "9432.0", "16,667",
" -322 ", "+4302", "(100);", "01FA" };
foreach (var value in values)
{
int number;
bool success = Int32.TryParse(value, out number);
if (success)
{
Console.WriteLine("Converted '{0}' to {1}.", value, number);
}
else
{
Console.WriteLine("Attempted conversion of '{0}' failed.",
value ?? "<null>");
}
}
}
}
// The example displays the following output:
// Attempted conversion of '<null>' failed.
// Converted '160519' to 160519.
// Attempted conversion of '9432.0' failed.
// Attempted conversion of '16,667' failed.
// Converted ' -322 ' to -322.
// Converted '+4302' to 4302.
// Attempted conversion of '(100);' failed.
// Attempted conversion of '01FA' failed.