共用方式為


支援參考傳回值 (Visual Basic)

C# 語言支持 參考傳回值。 了解參考傳回值的方法之一,就是它們與參考方法所傳遞的自變數相反。 修改藉由參考傳遞的參數時,變更會反映在呼叫端的變數值中。 當方法提供呼叫端的參考傳回值時,呼叫端對參考傳回值所做的修改會反映在呼叫方法的數據中。

Visual Basic 不允許您撰寫具有參考傳回值的方法,但可讓您取用參考傳回值。 換句話說,您可以使用參考傳回值呼叫方法,並修改該傳回值,而參考傳回值的變更會反映在呼叫方法的數據中。

直接修改 ref 回傳值

對於一律成功且沒有 ByRef 參數的方法,您可以直接修改參考傳回值。 為了達到這個目的,請將新值指派給返回參考返回值的表達式。

以下 C# 範例定義了一個方法,該方法會遞增一個內部值,並將其作為參考返回值傳回。

using System;

public class NumericValue
{
   private int value = 0;

   public NumericValue(int value)
   {
      this.value = value;
   }

   public ref int IncrementValue()
   {
      value++;
      return ref value;
   }

   public int GetValue()
   {
      return value;
   }
}

然後,呼叫端會在下列Visual Basic範例中修改參考傳回值。 請注意,具有方法呼叫的 NumericValue.IncrementValue 行不會將值指派給 方法。 相反地,它會將方法所傳回的參考型返回值指派給一個值。

Module Example
   Public Sub Main()
      Dim n As New NumericValue(15)
      n.IncrementValue() += 12
      Console.WriteLine(n.GetValue) 
   End Sub
End Module
' Output:   28

使用輔助方法

在其他情況下,直接修改方法呼叫的參考傳回值不一定是可取的。 例如,傳回字串的搜尋方法不一定會找到匹配項。 在此情況下,只有在搜尋成功時,才想要修改參考傳回值。

下列 C# 範例說明此案例。 它會定義 Sentence 以 C# 撰寫的類別,包括一個 FindNext 方法,該方法會在以指定的子字串開頭的句子中尋找下一個字。 字串會以參考傳回值的形式返回,而傳址至方法的 Boolean 變數會指出搜尋是否成功。 參考傳回值表示除了讀取傳回的值之外,呼叫端也可以修改它,而且修改會反映在類別內部 Sentence 所包含的數據中。

using System;

public class Sentence
{
    private string[] words;
    private int currentSearchPointer;

    public Sentence(string sentence)
    {
        words = sentence.Split(' ');
        currentSearchPointer = -1;
    }

    public ref string FindNext(string startWithString, ref bool found)
    {
        for (int count = currentSearchPointer + 1; count < words.Length; count++)
        {
            if (words[count].StartsWith(startWithString))
            {
                currentSearchPointer = count;
                found = true;
                return ref words[currentSearchPointer];
            }
        }
        currentSearchPointer = -1;
        found = false;
        return ref words[0];
    }

    public string GetSentence()
    {
        string stringToReturn = null;
        foreach (var word in words)
            stringToReturn += $"{word} ";

        return stringToReturn.Trim();
    }
}

在此情況下,直接修改返回值並不可靠,因為方法呼叫可能無法找到匹配項目,並返回句子中的第一個字。 在此情況下,呼叫端會不小心修改句子的第一個字。 呼叫端可以透過回傳 null(或在 Visual Basic 中回傳 Nothing)來防止問題。 但在此情況下,嘗試修改其值為 Nothing 的字串會擲出 NullReferenceException。 如果呼叫端傳回String.Empty也可以防止,但這需要呼叫端定義一個值為String.Empty的字串變數。 雖然呼叫端可以修改該字串,但修改本身沒有用途,因為修改過的字元串與類別所 Sentence 儲存句子中的單字沒有關聯性。

處理此情境的最佳方式是將參考的返回值通過參考的方式傳遞給輔助方法。 接著,Helper 方法會包含邏輯,以判斷方法呼叫是否成功,如果成功,則會修改參考傳回值。 下列範例提供可能的實作。

Module Example
   Public Sub Main()
      Dim sentence As New Sentence("A time to see the world is now.")
      Dim found = False
      Dim returns = RefHelper(sentence.FindNext("A", found), "A good", found) 
      Console.WriteLine(sentence.GetSentence()) 
   End Sub
   
   Private Function RefHelper(ByRef stringFound As String, replacement As String, success As Boolean) _ 
                    As (originalString As String, found As Boolean) 
      Dim originalString = stringFound
      If found Then stringFound = replacement
      Return (originalString, found)   
   End Function
End Module
' The example displays the following output:
'      A good time to see the world is now.

另請參閱