Sdílet prostřednictvím


Klíčové slovo ref

Klíčové slovo použijete ref v následujících kontextech:

  • V podpisu metody a ve volání metody předat argument metodě odkazem.
    public void M(ref int refParameter)
    {
        refParameter += 42;
    }
    
  • Pokud chcete v podpisu metody vrátit hodnotu volajícímu pomocí odkazu. Další informace najdete na webu ref return.
    public ref int RefMax(ref int left, ref int right)
    {
        if (left > right)
        {
            return ref left;
        }
        else
        {
            return ref right;
        }
    }
    
  • V deklaraci místní proměnné deklarujte odkazovou proměnnou.
    public void M2(int variable)
    {
        ref int aliasOfvariable = ref variable;
    }
    
  • Jako součást podmíněného výrazu odkazu nebo operátoru přiřazení odkazu.
    public ref int RefMaxConditions(ref int left, ref int right)
    {
        ref int returnValue = ref left > right ? ref left : ref right;
        return ref returnValue;
    }
    
  • struct V deklaraci deklarovat .ref struct Další informace najdete v ref článku o typech struktur.
    public ref struct CustomRef
    {
        public ReadOnlySpan<int> Inputs;
        public ReadOnlySpan<int> Outputs;
    }
    
  • ref struct V definici deklarujte ref pole. Další informace najdete v ref části pole článku o typech ref struktur.
    public ref struct RefFieldExample
    {
        private ref int number;
    }
    
  • V deklaraci obecného typu, která určuje, že typy parametrů allows ref struct typu.
    class RefStructGeneric<T, S>
        where T : allows ref struct
        where S : T
    {
        // etc
    }