为什么使用空的 get set 属性而不是使用公共成员变量? [英] Why have empty get set properties instead of using a public member variable?

查看:16
本文介绍了为什么使用空的 get set 属性而不是使用公共成员变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能的重复:
C#:公共字段与自动属性

重复?我认为不是:
这个问题与为什么使用属性而不是公共字段".具有指定属性的属性getter 和 setter 有很大的不同比公共领域.我的问题是,是一个属性WITHOUT 一个吸气剂和二传手,任何不同.

Duplicate? I think not:
This question is not the same as "Why use properties instead of public field". A property with a specified getter and setter is far different than a public field. My question was, is a property WITHOUT a getter and setter, any different.

由于最近可以使用空的 getter 和 setter,使用它们而不是仅仅声明一个公共成员变量有什么好处?

With the somewhat recent ability to have empty getters and setters, what is the benefit of using them instead of just declaring a public member variable?

示例:

public string MyProperty
{
    get;
    set;
}

对比:

public string MyProperty;

推荐答案

一个字:继承.

属性是可继承的,而字段则不是.您可以在继承的类中使用字段,但不能通过将它们设为虚拟来改变它们的行为.

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

像这样:

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; }
}

除了继承的事实外,其他答案中指出的要点(如可见性)也是属性优于字段的巨大好处.

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

这篇关于为什么使用空的 get set 属性而不是使用公共成员变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆