有一种方法可以创建一个带有自动创建使用引用的代码片段吗?

6

我用C#编写了一个简单的代码片段,它添加了一行代码。

Debug.WriteLine("");

现在的下一步是,在使用代码片段时,自动生成。
using System.Diagnostic;

有没有自动创建参考文献的方法? 我尝试设置片段引用和导入元素,如下所示:
<Snippet>
  <References>
    <Reference>
      <Assembly>System.dll</Assembly>
    </Reference>
  </References>
  <Imports>
    <Import>
      <Namespace>System.Diagnostic</Namespace>
    </Import>
  </Imports>
      .
      .
      .
</Snippet>

但是它不起作用


2
不是答案,但如果您想快速添加 using 语句,只需在类名上按下 CTRL + .,然后按 enter 选择要使用的语句即可。 - keyboardP
@keyboardP 嗯,如果我找不到更干净的方法来做这件事,我可能会在 Debug 之间使用结束光标,这样我就可以导入了。 - Fabio Marcolini
4个回答

1

很遗憾,Import 只适用于 VB 项目。这在 MSDN 上有解释。


1
奇怪,如果不是我亲眼看到,我绝对不会相信。 - Scott Chamberlain
1
Abe Heidebrecht 提供的链接已经失效。这是新的来源:MSDN - user8175891
现在支持C#(不确定从何时开始):https://learn.microsoft.com/en-us/visualstudio/ide/walkthrough-creating-a-code-snippet?view=vs-2017#add-references-and-imports - Caio Campos

1
有点晚了,但现在这适用于C# :)
<References>
    <Reference>
        <Assembly>System.dll</Assembly>
    </Reference>
</References>
<Imports>
    <Import>
       <Namespace>System.Diagnostic</Namespace>
    </Import>
</Imports>

将它们放在<Snippet>部分中。 文档甚至提到(这对C#也适用)

https://learn.microsoft.com/en-us/visualstudio/ide/walkthrough-creating-a-code-snippet?view=vs-2017#add-references-and-imports

PS:如果您想添加多个导入,可以这样做:

<Imports>
    <Import>
        <Namespace>System.Diagnostic</Namespace>
    </Import>
    <Import>
        <Namespace>System.Reflection</Namespace>
    </Import>
</Imports>

0
我查看了微软创建的mbox代码片段,并得出了以下结论:
<?xml version="1.0" encoding="utf-8"?>
<CodeSnippets xmlns="http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet">
   <CodeSnippet Format="1.0.0">
     <Header>
       <Title>dw</Title>
       <Shortcut>dw</Shortcut>
       <Description>Code snippet for System.Diagnostics.Debug.WriteLine</Description>
       <Author>MisaThinksMeDidIt</Author>
       <SnippetTypes>
         <SnippetType>Expansion</SnippetType>
       </SnippetTypes>         
     </Header>
     <Snippet>    
       <Declarations>
         <Literal>
            <ID>string</ID>
            <ToolTip>String to display</ToolTip>
            <Default>"Test"</Default>
         </Literal>
         <Literal Editable="false">
           <ID>SystemDiagnosticsDebugWriteLine</ID>
           <Function>SimpleTypeName(global::System.Diagnostics.Debug)</Function>
         </Literal>
       </Declarations>
       <Code Language="csharp"><![CDATA[$SystemDiagnosticsDebugWriteLine$.WriteLine($string$);$end$]]></Code>
     </Snippet>
  </CodeSnippet>
</CodeSnippets>

0
System.Diagnostics.Debug.WriteLine("");

你可以在代码片段中使用完全限定名称,而不是插入引用。


是的,我知道,但我想避免那个,我觉得那真的很丑。 - Fabio Marcolini

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接