How to avoid property recursion

后端 未结 5 1331
甜味超标
甜味超标 2020-12-16 09:08

This hit me recently on a project I was working on. Most people are familiar with property recursion:

public int Test 
{
   get { return this.test; }
   set          


        
5条回答
  •  南笙
    南笙 (楼主)
    2020-12-16 09:43

    Best way is to use "Auto implemented properties" here.

    public int Test { get; set; }
    

    If not possible to use "Auto implemented properties" for some reason use _ prefix(I don't prefer though).

    If you also don't prefer to use some prefixes, then you have other option. You don't have to write the property code by hand. Let the IDE do it for you; that way you can avoid careless mistakes. (I don't know how I missed this in original answer)

    Just type

    private int test;
    

    Select the field, Right click Refactor->Encapsulate Field. IDE will generate property snippet for you as below.

    public int Test
    {
        get { return test; }
        set { test = value; }
    }
    

    You don't need to bother clicking the context menu. If you prefer keyboard, shortcut is Ctrl + R + E.

    Or get a Resharper, It will point your silly mistake immediately.

提交回复
热议问题