How do I customize Visual Studio's private fie

2020-02-16 06:31发布

问题:

VS 2017 (and maybe olders versions) gives me this handy little constructor shortcut to generate a private readonly field and assign it.

Screenshot:

This ends up generating a private member called userService and then assigns it with:

this.userService = userService;

This goes against the code style that I use which is to name all private members with a prefix _ resulting in assignment that should look like:

_userService = userService;

How can I make it so that VS obeys this code style rule with its code generation shortcuts?

回答1:

This can be also achieved directly in Visual Studio. Just go to Tools -> Options -> Text Editor -> C# -> Code Style -> Naming.

  1. Firstly you need to define a new naming style by clicking the "Manage naming styles" button:

  1. Then click the + sign to define a new rule for "Private or Internal Field", that uses your new naming style:

  1. Restart Visual Studio

  2. After that, when you apply the "Create and initialize field" refactoring, it will be named with a leading underscore.



回答2:

The .editorconfig settings is kspearrin's answer didn't work for me I had to use these (for VS2017 Version 15.4.0):

[*.{cs,vb}]
dotnet_naming_rule.private_members_with_underscore.symbols  = private_fields
dotnet_naming_rule.private_members_with_underscore.style    = prefix_underscore
dotnet_naming_rule.private_members_with_underscore.severity = suggestion

dotnet_naming_symbols.private_fields.applicable_kinds           = field
dotnet_naming_symbols.private_fields.applicable_accessibilities = private

dotnet_naming_style.prefix_underscore.capitalization = camel_case
dotnet_naming_style.prefix_underscore.required_prefix = _

I got these from here: https://github.com/dotnet/roslyn/issues/22884#issuecomment-358776444



回答3:

This can be achieved by creating your own Roslyn Code Analyzer naming rule. Add a .editorconfig in your solution to specify custom naming conventions.

Read more about them here: https://docs.microsoft.com/en-us/visualstudio/ide/editorconfig-code-style-settings-reference

To get the desired effect from the question, the following will work:

[*.{cs,vb}]
dotnet_naming_rule.private_members_with_underscore.symbols  = private_fields
dotnet_naming_rule.private_members_with_underscore.style    = prefix_underscore
dotnet_naming_rule.private_members_with_underscore.severity = suggestion

dotnet_naming_symbols.private_fields.applicable_kinds           = field
dotnet_naming_symbols.private_fields.applicable_accessibilities = private
dotnet_naming_symbols.private_fields.required_modifiers         = readonly

dotnet_naming_style.prefix_underscore.capitalization = camel_case
dotnet_naming_style.prefix_underscore.required_prefix = _

Result: