[英]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? 由于我没有发现ReSharper是否能够为属性生成私有只读备份字段,有没有办法如何定义可以执行此操作的自定义脚本?
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 然后在这一行上设置一个光标,按Alt + Enter,会有一个菜单项将属性转换为
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 . 使用R#,您可以创建实时模板 。 In this case: 在这种情况下:
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. 在$SomeText$
包含文本将指定该文本作为R#的变量来进行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" 保存,您可以通过键入使用的快捷方式立即在Visual Studio中使用该模板,即“propReadOnly”
You could work the other way around with ReSharper
. 你可以用ReSharper
。
Create your private readonly backing field: 创建您的私有只读备份字段:
private readonly Type propertyName;
Then press alt + insert
to generate the property. 然后按alt + insert
以生成属性。
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. 然后按下alt + enter
,将光标放在fieldName上以创建字段。 You will then jump to the field and by pressing alt + enter
again Resharper
will make it a Constructor parameter. 然后,您将跳转到该字段,再次按alt + enter
, Resharper
将使其成为Constructor参数。 Last but not least you'll now get the option to press alt + enter
again to make the field readonly. 最后但并非最不重要的是,您现在可以选择再次按alt + enter
以使该字段只读。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.