简体   繁体   中英

Shortcut for creating constructor with variables (C# Visual Studio 2010)

In Visual Studio 2010 C# you can, in a class, type ctor and then press tab and Visual Studio will create a constructor for that class for me. It is very convenient.

But is there a way to make Visual Studio create a constructor with all my variables, properties and so on?

For example,

public class User
{
    public String UserName { get; private set; }
}

And for this I want ctor + tab to make me a

public User(string UserName)
{
    this.UserName = UserName;
}

You can sort of do this the other way around; if you start without the constructor or field, and try to use the non-existent constructor, you can press ctrl + . to ask it to generate one for you, usage-first:

在此输入图像描述

This compiler then generates something not too dissimilar:

public class User
{
    private string username;

    public User(string username)
    {
        // TODO: Complete member initialization
        this.username = username;
    }
}

You can then fix this up manually if needed (perhaps using the inbuilt rename refactor, etc). But not quite what you wanted.

I think what you are referring to is Code Snippets. You can write your own Code Snippets (they are written in XML). See here for a starting point.

You should also be able to edit existing Code Snippets (such as the ctor one). Refer to MSDN for some direction on this.

Note: Further Googling on Code Snippets will bring up more tutorials and references.

Thanks to Samuel Slade (telling me it's called code-snippets) I managed to find another Stack Overflow answer: Snippet code to create constructor in VS2010 Express

And it seems as the answer is NO , not without a plugin/extension.

Many refer to the ReSharper extension.

The "ctor" code snippet only creates a blank constructor, but does not use the existing attributes of the class in this constructor.

However, the latest versions of ReSharper enables you to choose the fields to be included in a constructor (like Eclipse does since a long time ago).

As others have noted, it is not possible to create snippets that are that intelligent.

There is a free Visual Studio add-in called Comet which can do what you want.

If you are using ReSharper the shortcut is Alt + Insert .

Source

I think you could do this with a snippet:

See Creating and Using IntelliSense Code Snippets (MSDN)

Use ReSharper's ctorf .

This will allow you to create a constructor with generated arguments based on fields defined in the class.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM