问题
I created a simple code snippet in c# which add the line
Debug.WriteLine("");
now the next step would be, when you use the snippet, to autocreate
using System.Diagnostic;
is there any way to automatically create the reference? I tried and set the snippets Reference and Import elements this way:
<Snippet>
<References>
<Reference>
<Assembly>System.dll</Assembly>
</Reference>
</References>
<Imports>
<Import>
<Namespace>System.Diagnostic</Namespace>
</Import>
</Imports>
.
.
.
</Snippet>
but it doesn't work
回答1:
Unfortunately, Import
only works for VB projects. It is explained on MSDN.
回答2:
A little late to the game, but this does work for C# now :)
<References>
<Reference>
<Assembly>System.dll</Assembly>
</Reference>
</References>
<Imports>
<Import>
<Namespace>System.Diagnostic</Namespace>
</Import>
</Imports>
Place those inside the <Snippet>
section.
The docs even mention (This works for C# as well.).
https://docs.microsoft.com/en-us/visualstudio/ide/walkthrough-creating-a-code-snippet?view=vs-2017#add-references-and-imports
PS: if you want to add more than one import, do it like this:
<Imports>
<Import>
<Namespace>System.Diagnostic</Namespace>
</Import>
<Import>
<Namespace>System.Reflection</Namespace>
</Import>
</Imports>
回答3:
System.Diagnostics.Debug.WriteLine("");
Instead of inserting a reference you could use the fully qualified name in your snippet.
回答4:
I had a look at the mbox snippet created by microsoft and came up with the following:
<?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>
来源:https://stackoverflow.com/questions/17408533/theres-a-way-to-create-a-code-snippet-with-automatically-create-a-using-referen