共用方式為


ref 關鍵字

您可以在下列內容中使用 ref 關鍵字:

  • 在方法簽章和方法呼叫中,藉傳址方式將引數傳遞給方法。
    public void M(ref int refParameter)
    {
        refParameter += 42;
    }
    
  • 在方法簽章中,以傳參考方式將值傳回給呼叫者。 如需詳細資訊,請參閱ref return
    public ref int RefMax(ref int left, ref int right)
    {
        if (left > right)
        {
            return ref left;
        }
        else
        {
            return ref right;
        }
    }
    
  • 在區域變數的宣告中,宣告參考變數
    public void M2(int variable)
    {
        ref int aliasOfvariable = ref variable;
    }
    
  • 作為條件式 ref 運算式ref 指派運算子的一部分。
    public ref int RefMaxConditions(ref int left, ref int right)
    {
        ref int returnValue = ref left > right ? ref left : ref right;
        return ref returnValue;
    }
    
  • struct 宣告中宣告 ref struct。 如需詳細資訊,請參閱 ref 結構類型一文。
    public ref struct CustomRef
    {
        public ReadOnlySpan<int> Inputs;
        public ReadOnlySpan<int> Outputs;
    }
    
  • ref struct 定義中,宣告 ref 欄位。 如需詳細資訊,請參閱 ref 結構類型一文的ref 欄位一節。
    public ref struct RefFieldExample
    {
        private ref int number;
    }
    
  • 在泛型型別宣告中,指定型別參數 allows ref struct 型別。
    class RefStructGeneric<T, S>
        where T : allows ref struct
        where S : T
    {
        // etc
    }