Visual Studio如何快速将代码嵌入自定义try-catch块?
在Visual Studio中自定义带日志输出的try-catch代码片段
你可以通过创建自定义代码片段的方式,实现选中代码后快速包裹成带日志的try-catch块,步骤如下:
一、创建自定义代码片段文件
新建一个XML文件,命名为TryCatchWithLog.snippet,填入以下内容:
<?xml version="1.0" encoding="utf-8"?> <CodeSnippets xmlns="http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet"> <CodeSnippet Format="1.0.0"> <Header> <Title>TryCatchWithLog</Title> <Shortcut>tryLog</Shortcut> <Description>将选中代码包裹到带日志输出的try-catch块</Description> <SnippetTypes> <SnippetType>SurroundsWith</SnippetType> </SnippetTypes> </Header> <Snippet> <Code Language="csharp"><![CDATA[ try { $selected$ } catch (Exception ex) { _log.Error($"[{message.GetType().Name}]:{ex}"); } ]]></Code> </Snippet> </CodeSnippet> </CodeSnippets>
<SnippetType>SurroundsWith</SnippetType>是核心配置,确保该片段可以用来包裹选中的代码。$selected$是占位符,会自动替换成你选中的代码。
二、导入并使用片段
- 打开Visual Studio,点击顶部菜单工具→代码片段管理器。
- 在管理器中,选择Visual C#→My Code Snippets,点击右侧的导入按钮。
- 选择你保存的
TryCatchWithLog.snippet文件,完成导入。 - 使用方式:
- 选中需要包裹的代码(比如
Do_Something();)。 - 右键点击选中的代码,选择环绕代码→找到你创建的
TryCatchWithLog;或者按下快捷键Ctrl+K,Ctrl+S,在弹出的列表中选择该片段。
- 选中需要包裹的代码(比如
三、(可选)修改默认try-catch片段(不推荐)
如果你想修改默认的try-catch片段,可按以下操作:
- 找到默认片段的路径(以Visual Studio 2022 Community为例):
C:\Program Files (x86)\Microsoft Visual Studio\2022\Community\VC#\Snippets\1033\Visual C#\try.snippet - 备份原文件后,打开该XML文件,将catch块内的
throw;替换为你的日志代码:catch (Exception ex) { _log.Error($"[{message.GetType().Name}]:{ex}"); } - 保存文件后,重启Visual Studio即可生效。
注意:该修改可能会在Visual Studio更新后被覆盖,因此更推荐使用自定义片段的方式。
内容的提问来源于stack exchange,提问作者Dominique
相关产品推荐
相关产品推荐

