DE CSharp Keyword ref - LIHACHTETAN/ClassicUO-Bad-Newbie-CSharp-Scripts-IDE GitHub Wiki
Українська · Русский · English · Deutsch · Français · Italiano · Español · 繁體中文 · 日本語 · 한국어
C#: ref
Handbuch C# · Praktischer Leitfaden
Übergibt einen Verweis auf eine Variable oder gibt ihn zurück. deklariert ref local, ref field und ref struct. Lebenszeitregeln erlauben es Ihnen nicht, einen Verweis auf eine lokale Variable zurückzugeben.
Einfaches Beispiel (Example.cs)
Speichern Sie dieses Beispiel separat als Example.cs. Führen Sie es unabhängig von den anderen Beispielen dieser Seite aus.
Example.cs:
// PROJECT-EXAMPLE
void Add(ref int value) { value += 2; }
int count = 3;
Add(ref count);
System.Console.WriteLine(count);
Ergebnis:
5
Syntax
Method(ref value) / ref int alias = ref value / ref struct Type
Beispiel 1: Grundform
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using System.IO;
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;
public static class Program
{
public static async Task Main(string[] args)
{
int number = 3;
Values.Increment(ref number);
Console.WriteLine(number);
}
}
public static class Values { public static void Increment(ref int value) { value++; } }
Beispiel 2: eine weitere praktische Form
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using System.IO;
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;
public static class Program
{
public static async Task Main(string[] args)
{
int[] values = [2, 4];
ref int first = ref Arrays.First(values);
first = 9;
Console.WriteLine(values[0]);
}
}
public static class Arrays { public static ref int First(int[] values) => ref values[0]; }
Beispiel 3
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using System.IO;
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;
public static class Program
{
public static async Task Main(string[] args)
{
int left = 2, right = 4;
ref int selected = ref (left > right ? ref left : ref right);
selected += 10;
Console.WriteLine($"{left}:{right}");
}
}
Beispiel 4
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using System.IO;
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;
public static class Program
{
public static async Task Main(string[] args)
{
int number = 3;
Reference holder = new(ref number);
holder.Value = 9;
Console.WriteLine(number);
}
}
public ref struct Reference { public ref int Value; public Reference(ref int value) { Value = ref value; } }
Offizielle Quelle: Microsoft Learn.