Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
204 views
in Technique[技术] by (71.8m points)

c# - Why have empty get set properties instead of using a public member variable?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

One word: inheritance.

Properties are inheritable while fields are not. You can use fields in an inherited class, but not alter their behavior by making them virtual.

Like so:

public class Foo {
  public virtual int MyField = 1; // Nope, this can't

  public virtual int Bar {get; set; }
}

public class MyDerive : Foo {
  public override MyField; // Nope, this can't

  public override int Bar {
    get {
      //do something;
    }
    set; }
}

Edit: Besides the fact of inheritance, the points pointed out in the other answers (like visibility) are also a huge benefit of properties over fields.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...