Using the value from the private variable or from

2019-06-08 07:08发布

When referencing class properties from a function within the class do you use the value from the actual property or the private variable value?

Which way is best? Why?

public class

  private m_Foo as double

  public property Foo() as double
    get
      return m_Foo
    end get
    set(byval value as double)
      m_Foo = value
    end set
  end property

  public function bar() as double
    Dim x as double = 5 * m_Foo
    Dim y as double = 3 * Foo
  end function

end class

6条回答
一夜七次
2楼-- · 2019-06-08 07:34

The property code may contain -- now or in the future -- logic that returns a different value or sets a different value depending on the state of the object. It makes sense to use the property.

查看更多
女痞
3楼-- · 2019-06-08 07:36

Two things.

First, this is a duplicate of

When should a class use its own getters/setters vs accessing the members directly?

Second, here's my article from earlier this year on a closely related subject:

http://blogs.msdn.com/ericlippert/archive/2009/01/14/automatic-vs-explicit-properties.aspx

查看更多
乱世女痞
4楼-- · 2019-06-08 07:36

Often the property contains simple logic, which you may miss out on accessing the variable directly.

public class MyClass 
{

   private List<string> _someList;

   public List<string> SomeString
   {
      get
      {
         if(_someList == null)
            _someList = new List<string>();
         return _someList;
      }
   }

}

if you then access _someList directly, you may run into a null reference. Accessing the property directly ensures it's been initialized.

Some may argue the private variable should have simply been declared as new in the first place, or initialized in the constructor rather than the property - but this should at least highlight a possible issue as this is a common approach.

查看更多
甜甜的少女心
5楼-- · 2019-06-08 07:43

It's probably safer (but not better) to use the property just in case you add additional get logic later on. Of course, adding logic to get for something that only yesterday was a 'plain' property probably isn't a good idea.

查看更多
Animai°情兽
6楼-- · 2019-06-08 07:46

I prefer the latter. If your property simply returns the field, the compiler will optimize your calls to it away. And you need to protect yourself against your own changes just like everyone else. What if the property later does something to the field before returning it, you'd have to update all your internal code to accommodate.

查看更多
闹够了就滚
7楼-- · 2019-06-08 07:50

Personally, I try to use the get/set accessor whenever possible, to avoid surprising myself when I change their logic and suddenly places where I access the private field don't work as expected.

查看更多
登录 后发表回答