简体   繁体   中英

Generate readonly field for property with ReSharper

Since I didn't find whether is ReSharper capable of generating a private readonly backing field for a property, is there a way how to define custom script that could do that?

Imagine you have a property

public Type PropertyName { get; set; }

and then you set a cursor on this line, press Alt+Enter and there would be a menu item which transforms the property to

private readonly Type propertyName;

public Type PropertyName { get { return propertyName; } }

I have found myself in the situation where I would actually use this many times.

With R#, you can create a Live Template . In this case:

  1. ReSharper > Templates Explorer
  2. Live Templates Tab > New Template (small grid icon)
  3. Shorcut: propReadOnly (this will be the shortcut used with intellisense)
  4. Description: whatever works for you...
  5. Available: in C# 2.0 where type member declaration is allowed
  6. Create the template as:

    private readonly $Type$ $propertyName$;

    public $Type$ $PropertyName$ { get { return $propertyName$; } }

Enclosing text in $SomeText$ will designate that text as a variable for R# to maninpulate.

In the variable name panel:

Name             Value             Editable Occurence
Type             Choose Macro*     #2
PropertyName     Choose Macro*     checkbox is checked
propertyName     (see below)       not editable
                 Macro > - Value of annother variable with the first character in lower case
                         - Select "PropertyName" as the other variable

*Choose Macro is displayed when no macro is selected; this is the default setting

Save and you can use the template immediately in Visual Studio by typing the shortcut used, ie, "propReadOnly"

You could work the other way around with ReSharper .

Create your private readonly backing field:

private readonly Type propertyName;

Then press alt + insert to generate the property.

Also see: Generating Properties

Edit:

Another option is to first create a property like this:

public MyProperty PropertyName { get { return propertyField;  } }

Then press alt + enter with your cursor on the fieldName to create the field. You will then jump to the field and by pressing alt + enter again Resharper will make it a Constructor parameter. Last but not least you'll now get the option to press alt + enter again to make the field readonly.

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