使用ReSharper为属性生成只读字段

Ond*_*cek 5 c# resharper properties

由于我没有发现ReSharper是否能够为属性生成私有只读备份字段,有没有办法如何定义可以执行此操作的自定义脚本?

想象一下,你有一个财产

public Type PropertyName { get; set; }
Run Code Online (Sandbox Code Playgroud)

然后在这一行上设置一个光标,按Alt + Enter键,会有一个菜单项将属性转换为

private readonly Type propertyName;

public Type PropertyName { get { return propertyName; } }
Run Code Online (Sandbox Code Playgroud)

我发现自己处于实际使用过多次的情况.

Met*_*urf 8

使用R#,您可以创建实时模板.在这种情况下:

  1. ReSharper>模板资源管理器
  2. 实时模板选项卡>新模板(小网格图标)
  3. Shorcut:propReadOnly(这将是intellisense使用的快捷方式)
  4. 描述:对你有用的......
  5. 可用:在C#2.0中允许类型成员声明
  6. 将模板创建为:

    private readonly $Type$ $propertyName$;

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

封闭文本$SomeText$将指定该文本作为R#的变量来进行操作.

在变量名称面板中:

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
Run Code Online (Sandbox Code Playgroud)

保存,您可以通过键入使用的快捷方式立即在Visual Studio中使用该模板,即"propReadOnly"