How to avoid property recursion

后端 未结 5 1342
甜味超标
甜味超标 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:44

    Could you not just write a test to cover this?

    int constructorValue = 4;
    TestClass test = new TestClass(constructorValue);
    Assert.Equals(test.Test, constructorValue);
    

    You may not want to write tests immediately to cover yourself from future wobbles, but you've found a bug, why not protect yourself from it again?

    For the record, if I need a private field to store the value for a pulic getter/setter, I always underscore it. There's just something an underscore that screams privacy!

    public string Test
    {
        get { return _test; }
        set { _test = value; }
    }
    
    private string _test;
    

提交回复
热议问题