Code snippet in vs to improve development efficiency

Source: Internet
Author: User
When talking about the templates in Vs, I introduced how to create a project/item template. This method can save a lot of repetitive work when creating a project, thus improving the development efficiency. After creating a project and a file, you have to start the specific code. At this time, there is a new repetitive job, that is, you need to frequently write similar or similar Code , We need a way to manage the code to reduce repeated input.

A common example is that when the for statement structure is used, such code may exist: Code
Int [] Array = { 1 , 2 , 3 , 4 , 5 };
For ( Int I =   0 ; I < Array. length; I ++ )
{
Console. writeline (array [I]);
}

Or

Code
List < String > Names =   New List < String > { " Anders " , " Bill " , " Clark " , " David " };
For ( Int I =   0 ; I < Names. Count; I ++ )
{
If (Names [I]. startswith ( " A " ))
{
Console. writeline (Names [I]);
}
}

Obviously, the code for these two for loops is very similar: input for, select a variable as the index, the variable has an upper limit, there are several parentheses and semicolons. This is also true for most for loops. How can we reduce repeated input? One way to think of this is to save the code of a for loop somewhere, for example, in a file, where the for is needed, and copy it in, modify the variable name, initial value, and upper limit.

Vs developers think very well and provide the code snippet function to realize the above ideas. It saves the for loop code template, and then gives it a shortcut key. Now in the editor (which must be a C # file), enter for and press the tab key twice in a row. The following code is displayed:

Except for the basic for code, the variable name is also located. If you need to modify the variable name, if you change it to index, the next two I will be automatically changed to index, and then press tab, the cursor will jump to the next dark color display, that is, length. Here you can modify the index upper limit, and press Enter. The cursor will jump to the Code body of the For Loop:

Is it convenient? There are many other snippet, such as entering CW, and pressing the tab twice to display console. writeline ().

Most of the time, the same function is different in different languages, so code snippet (hereinafter referred to as SNIPPET) is language-specific, that is, C # snippet cannot be used in VB.. net. Snippet in vs2008 supports C #, VB. NET, and XML.

Snippet Management

First, vs2008 provided a lot of built-in snippet. In addition, we can also import self-written or compiled by others into. Choose tools> code snippets Manager (or press Ctrl + k, CTRL + B) to open the code snippets manager window:

You can see the language list above. The selected language is C #. You can import a new snippet using the import method. When using nunit, due to the characteristics of the test code, there will be a lot of Repeated input, so Scott bellware provides nunit snippet, and I put it in my own blog: bellwarenunitsnippet. Now import the. snippet file in the package.

Well, you can use it. For example, input TC and press TAB twice. The Code is as follows:

Enter the testcase name and press enter to enter the test code. Observe this snippet. There is only one change, that is, testcase.

Next we will analyze the structure of the snippet file so that we can write our own snippet.

Snippet definition file parsing

Next let's take a look at how snippet is implemented. Based on the TC example above, we can guess that to store snippet, at least the template code, placeholders, language types, and shortcuts are required. This is true for Each snippet. In fact, vs stores the information in the XML file, which corresponds to some nodes. This is similar to the template list file in the previous article.

The file that stores snippet is an XML file, but its extension is. snippet. An snippet file can contain multiple snippet files, just like the preceding bellwarenunit. snippet file. Its basic structure is as follows:

XML Code
<? XML version = "1.0" encoding = "UTF-8" ?>
< Codesnippets Xmlns = "Http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet" >
< Codesnippet Format = "1.0.0" >
< Header >
< Title > Code snippet for Debug. writeline method. </ Title >
< Shortcut > DW </ Shortcut >
< Author > Anders Cui </ Author >
</ Header >
< Snippet >
< Code Language = "CSHARP" >
<! [CDATA [
Debug. writeline ("text ");
]>
</ Code >
</ Snippet >
</ Codesnippet >
<! -- Other snippets -->
</ Codesnippets >

Create an XML file and enter the above Code. Here, we enter the Debug. writeline code for snippet. The root node of the file is codesnippets, which can contain multiple <codesnippet> nodes. Note that it is much easier to edit the namespace in.

Important<Codesnippet>Node, which indicates an snippet. It must contain a format attribute, which is used to represent the snippet version. In addition, it must contain two subnodes:<Header>And<Snippet>.

For

For more information about

For <snippet> nodes, it is the place where the code template is implemented. It contains four subnodes.

1. <code> node

    • Delimiter: delimiter. The default value is $. You will see its usage later.
    • Kind: the type of snippet, such as method body, method declaration, and type declaration.
    • Language: applicable language types, such as C #, VB. NET, and XML.

In our above example, we already have a code node. Note that the code is included in <! [CDATA []>, because the code may contain some special characters.

In the above Tc snippet, after pressing the tab, Vs will select testcase, which is more convenient to modify. For DW snippet above, we naturally want vs to select "text, this requires the following <declarations> node.

2. <declarations> node

This node contains several <literal> and <Object> nodes. They can be seen as placeholders. <Literal> is used to specify some text values. <Object> is used to declare objects in the template.
For more information, see <literal> and <Object>.

Here we need to regard "text" as a placeholder, so add a <literal> node:

XML Code
< Snippet >
< Code Language = "CSHARP" >
<! [CDATA [
Debug. writeline ($ text $); $ end $
]>
</ Code >
< Declarations >
< Literal >
< ID > Text </ ID >
< Tooltip > Text to write </ Tooltip >
< Default > "Text" </ Default >
</ Literal >
</ Declarations >
</ Snippet >

A placeholder $ text $ is added here. The default value is "text ",$ End $ at the end of a row is a special placeholder, which indicates the cursor position after you press Enter..

3. <imports> node

It is used to specify the namespace reference that should be added to the file when using snippet, but only supports VB. NET.

4. <references> node

Used to specifyProgramSet Reference, also only support VB. NET :(

Now we can test our snippet. Save the file as the. snippet file and import it.


Not bad?

Code snippet Function

As mentioned above, <imports> and <references> nodes can only be used for VB. NET, while the code snippet function here can only be used for C #.

Both the <literal> and <Object> nodes contain subnodes.<Function>These functions are part of Vs and sometimes useful. There are three functions:

1. generateswitchcases (enumerationliteral) generates a switch statement and a series of case statements based on the provided Enumeration type. In fact, there is an example in C:

Press enter to confirm:

2. classname (), return the name of the class where snippet is located.

3. simpletypename (typename): in the context where snippet is located, the simplest form of the typename parameter is deduced.
The following uses simpletypename as an example to illustrate the usage of these functions:

XML Code
< Snippet >
< Code Language = "CSHARP" >
<! [CDATA [
$ Nameofdebug $. writeline ($ text $); $ end $
]>
</ Code >
< Declarations >
< Literal >
< ID > Text </ ID >
< Tooltip > Text to write </ Tooltip >
< Default > "Text" </ Default >
</ Literal >
< Literal Editable = "False" >
< ID > Nameofdebug </ ID >
< Function > Simpletypename (Global: system. Diagnostics. Debug) </ Function >
</ Literal >
</ Declarations >
</ Snippet >

Here we have added a literal to snippet. Why do we need to do this? We know that the system. Diagnostics namespace is not referenced by default. If you use the debug class, you also need to reference system. diagnostics. The trick here is that Vs will infer the simplest form of nameofdebug. If system. Diagnostics is not referenced, it will be added before debug, otherwise it will not be added.

Several Suggestions

First, snippet is defined in XML, so it can be regarded as code. Therefore, in terms of naming, You must select a more meaningful or relevant name. One way to name a shortcut key is to use the abbreviation of the first letter, suchAssert. areequal (expected, actual );Is AE.

In addition, remember to enter the content of the tooltip node, which will be displayed when using snippet.

Other tools

Although snippet can simplify code input, it is not very convenient to write it. It is better to use some visualization tools, such as snippet editor. If you are interested, try it.

In addition, many people in this world are writing snippet, such as gotcodesnippets.com, so you can search for it before writing it :)

Summary

This article describes how to use and compile code snippet. It can be seen as a code snippet template with a smaller granularity than the project/item template, which further improves work efficiency.

Reference

Professional Visual Studio 2008 extensibility

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.