Share via


擷取方法重構

此重構適用於:

  • C#

  • Visual Basic

功能:讓您將程式碼片段轉換成它自己的方法。

時機:您在某個必須從另一個方法來呼叫的方法中有現有的程式碼片段。

原因:您可以複製/貼上該程式碼,但那樣會造成重複。 較好的解決方案是將該片段重構成它自己的且可由任何其他方法自由呼叫的方法。

操作方式

  1. 醒目標示的擷取的程式碼:

    • C#:

      Screenshot showing C# code for the Program class. In the Main function of that class, a line of code highlighted.

    • Visual Basic:

      Screenshot showing Visual Basic code for the Main Sub. In that Sub, a line of code is highlighted.

  2. 接著,執行下列其中一項操作:

    • 鍵盤
      • CTRL+R,再按 CTRL+M。 (請注意,根據您所選取的設定檔,鍵盤快速鍵可能會不同)。
      • 按下 Ctrl+. 以觸發 [快速動作與重構] 功能表,然後從 [預覽] 快顯視窗中選取 [擷取方法]
    • 滑鼠
      • 選取 [編輯] > [重構] > [擷取方法]
      • 以滑鼠右鍵按一下該程式碼,然後選取 [重構] > [擷取] > [擷取方法]
      • 在程式碼上按一下滑鼠右鍵,選取 [快速動作與重構] 功能表,然後從 [預覽] 快顯視窗中選取 [擷取方法]

    系統將會立即建立方法。 從這裡,您現在即可輸入新名稱來為方法重新命名。

    提示

    您也可以使用出現在 IDE 右上角 [重新命名] 方塊中的核取方塊,以更新註解和其他字串來使用這個新名稱,以及在儲存前先預覽變更

    • C#:

      Screenshot showing C# code for the Program class. A method name is highlighted and the Rename popup window is open.

    • Visual Basic:

      Screenshot showing Visual Basic code for the Main Sub. A method name is highlighted and the Rename popup window is open.

  3. 當您對變更感到滿意時,請選擇 [套用] 按鈕或按 ENTER,便會認可變更。

另請參閱