重構Refactoring

重構程式碼是重新排列、重建和釐清現有程式碼的方法,並能同時確保程式碼的整體行為不會變更。Refactoring code is a way to rearrange, restructure, and clarify existing code while ensuring that the overall behavior of the code doesn't change.

重構會產生較健康的程式碼基底,以讓您、任何其他開發人員或可能參考程式碼的使用者更容易使用、讀取和維護它。Refactoring produces a healthier code base, making it more useable, readable, and maintainable for you or any other developer or user that might refer to the code.

Visual Studio for Mac 與 Roslyn (Microsoft 的開放原始碼 .NET 編譯器平台) 的整合,可讓您進行更多重構作業。Visual Studio for Mac's integration with Roslyn, Microsoft's open-source .NET compiler platform, allows for more refactoring operations.

重新命名Renaming

[重新命名] 重構命令可以用於任何程式碼識別碼 (例如,類別名稱、屬性名稱等等),以尋找該識別碼的所有出現項目並進行變更。The Rename refactoring command can be used on any code identifier (for example, a class name, property name etc.) to find all occurrences of that identifier and change them. 若要重新命名符號,請以滑鼠右鍵按一下它,然後選擇 [重構] > [重新命名],或 Cmd + R 按鍵繫結關係:To rename a symbol, right-click on it and choose Refactor > Rename, or the Cmd + R key binding:

重新命名功能表項目

這將醒目提示符號和其任何參考。This highlights the symbol and any references to it. 當您開始鍵入新名稱時,將自動變更您程式碼中的所有參考,並藉由按 Enter 以發出重新命名完成的訊號:When you start typing a new name it automatically changes all references in your code, and you can signal your completion of the rename by pressing Enter:

重新命名和識別碼

內容動作Context actions

內容動作可讓您檢查任何 C# 程式碼,並查看所有可能的重構選項。Context actions allow you to inspect any C# code, and see all possible refactoring options.

[解析] 和 [重構] 內容項目會合併至可提供所有可用內容動作的單一 [快速檢修] 項目:The Resolve and Refactor context items are combined into a single Quick Fix... item that will provide you with all the available Context actions:

顯示內容項目

將滑鼠游標移至任何內容動作上方,會提供從程式碼所新增或移除項目的預覽。Hovering over any of the context actions provides you with a preview of what will be added or removed from your code.

或者,您可以在程式碼中的任何位置按 Option + EnterAlternatively, you can press Option + Enter anywhere in your code:

選項輸入內容項目

若要啟用這些選項,您必須選取 [Visual Studio for Mac] > [喜好設定] > [文字編輯器] > [來源分析] 選項中的 [啟用開啟檔案的來源分析]:To enable these options, you must select Enable source analysis of open files in the options Visual Studio for Mac > Preferences > Text Editor > Source Analysis:

啟用來源分析

可建議超過 100 個可能的動作,其啟用或停用方式是瀏覽至 [Visual Studio for Mac] > [喜好設定] > [來源分析] > [C#] > [程式碼動作],並選取或取消選取動作旁的方塊:There are over 100 possible actions that can be suggested, which are enabled or disabled by browsing to Visual Studio for Mac > Preferences > Source Analysis > C# > Code Actions and selecting or unselecting the box next to the action:

C# 來源分析動作

一般內容動作Common context actions

下面將說明一些最常用內容動作。Some of the mostly commonly used context actions are explained below.

擷取方法Extract method

擷取方法重構作業可讓您擷取現有成員中的程式碼選取項目來建立新的方法。The extract method refactoring operation allows you to create a new method by extracting a selection of code in an existing member. 此動作將會執行兩個作業:This action will do two things:

  • 建立包含所選取程式碼的新方法Creates a new method containing the selected code
  • 在所選取程式碼所在的位置中,呼叫新方法。Calls the new method in the place where the selected code was.
範例Example
  1. 加入下列程式碼:Add the following code:
    class MainClass
    {

        double CalculatePyramidVolume(double baseArea, double height)
        {

            double volume = (baseArea * height) / 3;

            return volume;
        }
    }
  1. 反白顯示 double volume = (baseArea * height) / 3; 這行,並以滑鼠右鍵按一下它,然後選取 [重構] > [擷取方法]。Highlight the line double volume = (baseArea * height) / 3;, right click on it, and select Refactor > Extract Method.

  2. 使用方向鍵來選取新方法在程式碼中的位置。Use the arrow keys to select where the new method should be placed in your code.

封裝欄位Encapsulate field

[封裝欄位] 作業可讓您從現有欄位建立屬性,並更新您的程式碼以參考新建立的屬性。The Encapsulate Field operation allows you to create a property from an existing field, and updates your code to reference the newly created property. 建立可封裝您欄位的屬性,即會禁止直接存取您的公用欄位,這表示其他物件無法修改它。By creating a property that encapsulates your field, you are disallowing direct access to your public field, meaning that other objects can't modify it.

此動作將會執行下列作業:This action will do the following:

  • 將存取修飾詞變更為私用。Changes the access modifier to private.
  • 產生欄位的 getter 和 setter (除非欄位為唯讀,在此情況下,它只會建立 getter)。Generates a getter and setter for the field (unless the field is read-only, in which case it will only create a getter).

來源分析Source analysis

來源分析透過將潛在錯誤和樣式違規加上底線,並將自動修正提供為內容動作,來即時分析您的程式碼。Source analysis analyzes your code on the fly by underlining potential errors and style violations, and providing auto fixes as context actions.

檢視文字編輯器右側的捲軸,即可隨時檢視任何檔案的所有來源分析結果:You can view all results of the source analysis for any file, at any time, by viewing the scroll bar on the right side of the text editor:

來源分析提要欄位

如果您按一下頂端的圓圈,則可以逐一查看每項建議,而最高嚴重性問題會顯示在最前面。If you click on the circle at the top, you can iterate through each suggestion, with the highest severity issues showing first. 將滑鼠游標移至個別結果或個別行上方即會顯示問題,這可透過內容動作進行修正:Hovering over an individual result or line displays the issue, which can be fixed through context actions:

來源分析項目

另請參閱See also