Code snippet or shortcut to create a constructor in Visual Studio

前端 未结 17 1600
悲哀的现实
悲哀的现实 2020-12-23 12:57

What is the code snippet or shortcut for creating a constructor in Visual Studio?

Visual Studio 2010 and C#.

相关标签:
17条回答
  • 2020-12-23 13:28

    In case you want a constructor with properties, you need to do the following:

    1. Place your cursor in any empty line in a class;

    2. Press Ctrl + . to trigger the Quick Actions and Refactorings menu;

    3. Select Generate constructor from the drop-down menu;

    4. Pick the members you want to include as constructor parameters. You can order them using the up and down arrows. Choose OK.

    The constructor is created with the specified parameters.

    Generate a constructor in Visual Studio

    0 讨论(0)
  • 2020-12-23 13:35

    Simply type ctor then press TAB.

    0 讨论(0)
  • 2020-12-23 13:36

    I don't know about Visual Studio 2010, but in Visual Studio 2008 the code snippet is 'ctor'.

    0 讨论(0)
  • 2020-12-23 13:36

    Type ctor and Tab.

    ََََََََََ

    0 讨论(0)
  • 2020-12-23 13:36

    Should you be interested in creating the 'ctor' or a similar class-name-injecting snippet from scratch, create a .snippet file in the C# snippets directory (for example C:\VS2017\VC#\Snippets\1033\Visual C#\C#Snippets.snippet) with this XML content:

    <CodeSnippets>
        <CodeSnippet>
            <Header>
                <Title>ctor</Title>
                <Shortcut>ctor</Shortcut>
            </Header>
            <Snippet>
                <Declarations>
                    <Literal Editable="false"><ID>classname</ID><Function>ClassName()</Function></Literal>
                </Declarations>
                <Code>
                    <![CDATA[public $classname$($end$)
                    {
    
                    }]]>
                </Code>
            </Snippet>
        </CodeSnippet>
    </CodeSnippets>
    

    This snippet injects the current class name by way of calling C# code snippet function ClassName(), detailed on this docs.microsoft page.

    The end result of expanding this code snippet:

    0 讨论(0)
  • 2020-12-23 13:37

    In Visual Studio 2010, if you type "ctor" (without the quotes), IntelliSense should load, showing you "ctor" in the list. Now press TAB twice, and you should have generated an empty constructor.

    0 讨论(0)
提交回复
热议问题