ref(C# 참조)
다음과 같은 상황에서 ref
키워드를 사용합니다.
- 메서드 시그니처 및 메서드 호출에서 인수를 메서드에 참조로 전달합니다.
class TheClass
{
public string? willIChange;
}
struct TheStruct
{
public string willIChange;
}
class TestClassAndStruct
{
static void ClassTaker(TheClass c)
{
c.willIChange = "Changed";
}
static void StructTaker(TheStruct s)
{
s.willIChange = "Changed";
}
public static void Main()
{
TheClass testClass = new TheClass();
TheStruct testStruct = new TheStruct();
testClass.willIChange = "Not Changed";
testStruct.willIChange = "Not Changed";
ClassTaker(testClass);
StructTaker(testStruct);
Console.WriteLine("Class field = {0}", testClass.willIChange);
Console.WriteLine("Struct field = {0}", testStruct.willIChange);
}
}
/* Output:
Class field = Changed
Struct field = Not Changed
*/
- 메서드 시그니처에서 값을 호출자에게 참조로 반환합니다. 자세한 내용은
ref return
를 참조하세요.
int[] xs = new int [] {10, 20, 30, 40 };
ref int found = ref FindFirst(xs, s => s == 30);
found = 0;
Console.WriteLine(string.Join(" ", xs)); // output: 10 20 0 40
ref int FindFirst(int[] numbers, Func<int, bool> predicate)
{
for (int i = 0; i < numbers.Length; i++)
{
if (predicate(numbers[i]))
{
return ref numbers[i];
}
}
throw new InvalidOperationException("No element satisfies the given condition.");
}
- 지역 변수 선언에서 참조 변수를 선언합니다.
ref int aliasOfvariable = ref variable;
void Display(double[] s) => Console.WriteLine(string.Join(" ", s));
double[] arr = { 0.0, 0.0, 0.0 };
Display(arr);
ref double arrayElement = ref arr[0];
arrayElement = 3.0;
Display(arr);
arrayElement = ref arr[arr.Length - 1];
arrayElement = 5.0;
Display(arr);
// Output:
// 0 0 0
// 3 0 0
// 3 0 5
struct
선언에서ref struct
를 선언합니다. 자세한 내용은ref
구조체 형식 문서를 참조하세요.
public ref struct CustomRef
{
public bool IsValid;
public Span<int> Inputs;
public Span<int> Outputs;
}
ref struct
정의에서ref
필드를 선언합니다. 자세한 내용은ref
구조체 형식 문서의ref
필드 섹션을 참조하세요.
public ref struct RefFieldExample
{
private ref int number;
public int GetNumber()
{
if (System.Runtime.CompilerServices.Unsafe.IsNullRef(ref number))
{
throw new InvalidOperationException("The number ref field is not initialized.");
}
return number;
}
}
- 제네릭 형식 선언에서 형식 매개 변수
allows ref struct
의 형식을 지정합니다.
class SomeClass<T, S>
where T : allows ref struct
where S : T
{
// etc
}
GitHub에서 Microsoft와 공동 작업
이 콘텐츠의 원본은 GitHub에서 찾을 수 있으며, 여기서 문제와 끌어오기 요청을 만들고 검토할 수도 있습니다. 자세한 내용은 참여자 가이드를 참조하세요.
.NET