繁体   English   中英

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

[英]Generate readonly field for property with ReSharper

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

想象一下,你有一个财产

public Type PropertyName { get; set; }

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

private readonly Type propertyName;

public Type PropertyName { get { return propertyName; } }

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

使用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#的变量来进行maninpulate。

在变量名称面板中:

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

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

你可以用ReSharper

创建您的私有只读备份字段:

private readonly Type propertyName;

然后按alt + insert以生成属性。

另请参阅: 生成属性

编辑:

另一个选择是首先创建一个这样的属性:

public MyProperty PropertyName { get { return propertyField;  } }

然后按下alt + enter ,将光标放在fieldName上以创建字段。 然后,您将跳转到该字段,再次按alt + enterResharper将使其成为Constructor参数。 最后但并非最不重要的是,您现在可以选择再次按alt + enter以使该字段只读。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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