Megosztás a következőn keresztül:


A ref kulcsszó

A kulcsszót a ref következő kontextusokban használja:

  • Metódus-aláírásban és metódushívásban, hogy hivatkozással adjon át egy argumentumot egy metódusnak.
public void M(ref int refParameter)
{
    refParameter += 42;
}
  • Metódusadákban egy értéket kell visszaadnia a hívónak hivatkozással. További információ: ref return.
public ref int RefMax(ref int left, ref int right)
{
    if (left > right)
    {
        return ref left;
    }
    else
    {
        return ref right;
    }
}
  • Egy helyi változó deklarációjában egy referenciaváltozó deklarálása.
public void M2(int variable)
{
    ref int aliasOfvariable = ref variable;
}
public ref int RefMaxConditions(ref int left, ref int right)
{
    ref int returnValue = ref left > right ? ref left : ref right;
    return ref returnValue;
}
  • struct A deklarációban deklaráljon egy ref struct. További információt a struktúratípusokról szóló ref cikkben talál.
public ref struct CustomRef
{
    public ReadOnlySpan<int> Inputs;
    public ReadOnlySpan<int> Outputs;
}
public ref struct RefFieldExample
{
    private ref int number;
}
  • Egy általános típusdeklarációban adja meg, hogy egy típusparaméter allows ref struct típusa legyen.
class RefStructGeneric<T, S>
    where T : allows ref struct
    where S : T
{
    // etc
}