您可以在下列內容中使用 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 }