1. 內嵌聊天-現場編輯程式碼
內嵌聊天 允許您開啟一個小提示 就在編輯器中,描述您想要的更改,Copilot 將就地編輯程式碼,而無需切換到聊天視圖。
開啟內嵌聊天
- 蘋果系統:
指令+I - Windows/Linux:
Ctrl+I
基本工作流程:
- 選擇(select)你要編輯的程式碼(或將遊標放在你要新增程式碼的位置)
- 新聞
指令+I - 用英語/越南語輸入變更說明
- 查看差異顯示內聯
- 新聞 接受 或 丟棄
2. 內嵌聊天的常見用例
2.1.新增錯誤處理
// Select function này → Cmd+I → "Add try-catch error handling with proper logging"async function fetchUserData(userId: string) { const response = await fetch(
/api/users/${userId}); const data = await response.json(); return data; }
// Copilot sẽ suggest: async function fetchUserData(userId: string) { try { const response = await fetch(/api/users/${userId}); if (!response.ok) { throw new Error(HTTP error! status: ${response.status}); } const data = await response.json(); return data; } catch (error) { console.error(Failed to fetch user ${userId}:, error); throw error; } }
2.2.重構程式碼
# Select block code → Cmd+I → "Refactor to use list comprehension"Trước:
result = [] for item in items: if item.price > 100: result.append(item.name)
Sau (Copilot suggest):
result = [item.name for item in items if item.price > 100]
2.3.新增 TypeScript 類型
// Select → Cmd+I → "Add TypeScript type annotations"// Trước: function processOrder(order, discount) { const total = order.items.reduce((sum, item) => sum + item.price, 0); return total * (1 - discount); }
// Sau: interface OrderItem { id: string; name: string; price: number; }
interface Order { id: string; items: OrderItem[]; }
function processOrder(order: Order, discount: number): number { const total = order.items.reduce((sum, item) => sum + item.price, 0); return total * (1 - discount); }
2.4.生成文檔
# Select function → Cmd+I → "Add docstring with parameters and return type" def calculate_compound_interest(principal, rate, time, n=12): """ Calculate compound interest.Args: principal (float): Initial investment amount. rate (float): Annual interest rate (as a decimal, e.g., 0.05 for 5%). time (float): Time period in years. n (int): Number of times interest is compounded per year. Defaults to 12. Returns: float: The total amount after compound interest. """ return principal * (1 + rate / n) ** (n * time)
2.5.編寫單元測試
// Select function → Cmd+I → "Generate unit tests using Jest"
// Copilot tự sinh test cases bao gồm happy path, edge cases, error cases
3. 智慧行動-人工智慧融入工作流程
智慧行動是人工智慧行動 內建 進入 VS Code 介面,無需打開聊天即可出現在您需要的地方。
3.1.產生提交訊息
- 開放原始碼控制視圖(
Ctrl+Shift+G) - 階段性改變
- 點選 閃閃發光的圖標✨ 在提交訊息輸入旁邊
- Copilot 分析變更並根據常規提交產生提交訊息
// Ví dụ generated commit message:
feat(auth): add JWT token refresh mechanism
- Add refreshToken endpoint to AuthController
- Implement token rotation with configurable expiry
- Add middleware to auto-refresh expired tokens
3.2.與副駕駛一起修復(快速修復)
當 VS Code 顯示錯誤時(波浪形紅線):
- 將滑鼠懸停在錯誤上 → 單擊 “快速修復”
- 選擇 “與副駕駛一起修復”
- Copilot 讀取錯誤訊息、分析上下文並提出修復建議
3.3.與副駕駛解釋
選擇複雜程式碼→右鍵→ “副駕駛”→“解釋一下”
Copilot 用自然語言解釋程式碼,這在閱讀其他人的程式碼或人工智慧產生的程式碼時非常有用。
3.4.生成測試
右鍵單擊函數 → “副駕駛”→“生成測試”
Copilot 會自動建立測試文件,其中包含與專案框架相符的測試案例(Jest、Pytest、Go 測試...)。
3.5.修復測試失敗
當測試資源管理器中的測試失敗時:
- 點擊失敗的測試
- 選擇 “與副駕駛一起修復”
- Copilot 讀取測試失敗訊息,找到根本原因,並建議程式碼修復(不是測試修復)
4. VS Code 中的語意搜尋
提供副駕駛 語意搜尋 — 按含義搜索,而不僅僅是文字匹配:
// Traditional search: tìm "authenticate"
// Kết quả: chỉ những chỗ có chính xác từ "authenticate"
// Semantic search: tìm "user login process"
// Kết quả: authenticate(), verifyCredentials(), signIn(), checkPassword()
// → Tìm được code liên quan dù không match exact text
5. 何時使用內聯聊天、代理或聊天?
| 特點 | 何時使用 | 適用範圍 |
|---|---|---|
| 內嵌建議 | 程式碼流不間斷 | 目前行/區塊 |
| 內嵌聊天 | 具體編輯、重構、新增文檔 | 選定的代碼或遊標位置 |
| 聊天視圖(詢問) | 問答、解釋、腦力激盪 | 不要更改程式碼 |
| 代理模式 | 建置功能、多文件更改 | 整個專案 |
Scope nhỏ → lớn:
Inline Suggestions → Inline Chat → Chat (Ask) → Agent Mode
(line) (selection) (Q&A) (project)
6. 有效內嵌聊天的技巧
- 正確選擇:選出正確的一段程式碼進行編輯,既不多餘也不遺漏
- 清晰的描述:「新增電子郵件和電話的輸入驗證」比「驗證此」更好
- 一次改變一個:將一個大的變化分解為許多小的內聯聊天
- 使用代碼術語:“提取到輔助函數”而不是“將其分開”
- 接受前審查: 仔細閱讀 diff,尤其是更改邏輯
7.練習練習
建立文件 智慧操作實務.ts:
// Bài tập 1: Select function → Cmd+I → "Add error handling"
function divideNumbers(a, b) {
return a / b;
}
// Bài tập 2: Select → Cmd+I → "Convert to arrow function with types"
function greetUser(name) {
return "Hello, " + name + "!";
}
// Bài tập 3: Select → Cmd+I → "Add JSDoc documentation"
function calculateDiscount(price, percentage, maxDiscount) {
const discount = price * percentage / 100;
return Math.min(discount, maxDiscount);
}
// Bài tập 4: Tạo git commit → dùng ✨ để generate commit message
// Bài tập 5: Tạo lỗi cố ý → dùng "Fix with Copilot" để sửa
八、總結
內嵌聊天和智慧操作是工具 精準編輯 — 允許您:
- ✅ 快速重構程式碼
- ✅ 只需一個提示即可新增錯誤處理、類型、文檔
- ✅ 透過完整上下文修復錯誤
- ✅ 智慧產生提交訊息
- ✅ 保持編碼流程而不切換上下文
在下一節中(第2部分),我們將進入 Copilot 最強大的功能 — 代理模式,人工智慧會自動編寫程式碼、建立檔案、運行命令並建立完整的功能。