为什么需要使用get和set? [英] Why do I need to use get and set?

查看:344
本文介绍了为什么需要使用get和set?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个code段:

public class MyClass
{
    private string _myProperty;

    public string MyProperty
    {
        get
        {
            return _myProperty;
        }

        set
        {
            _myProperty = value;
        }
    }
}

有什么意义吗?我可以宣布 _myProperty 字符串作为公众和我的任何类对象就能直接访问他们,并获取或设置值。

What is the point here? I could have declared the _myProperty string as public and any of my class objects will be able to directly access them and get or set the value.

相反,我们正在 _myProperty 私人和使用get和set访问它们,使用类对象。

Instead, we are making _myProperty private and the using get and set to access them, using the class object.

在任一情况下,这个类对象是能够访问它们,结果总是相同。

In either case, the class object is able to access them and the result is always same.

那么,为什么用这种方式?那是唯一的,因为我可以在二传手实施一些限制?

So why use this approach? Is that only because I can implement few constraints in setter?

除此之外什么危害会使得成员变量的公共事业?在这个例子中,我可能会暴露 _myProperty 作为公众,而不是仅仅通过使私人,作为OOP建议把它限制为这一类。

Apart from that what harm will making member variables public cause? In this example I could expose _myProperty as public instead of restricting it to this class only by making it private, as OOP would suggest.

推荐答案

没有,结果的不是的总是相同的。

No, the result isn't always the same.

  • 尝试结合到公共领域(或做它使用反射和预计性能别的)
  • 尝试通过属性引用(不能)
  • 尝试的之后的决定你想要记录等,并发现,当将其更改为一个属性,你失去了源代码和二进制兼容性。
  • Try binding to a public field (or doing anything else which uses reflection and expects properties)
  • Try passing a property by reference (you can't)
  • Try later deciding you want logging etc and finding that when you change it to a property, you lose both source and binary compatibility.

阅读文章中,我前一段时间写了这个的...

请注意,由于C#2你的code可以是很多的短虽然:

Note that as of C# 2 your code can be a lot shorter though:

public class MyClass
{
    public string MyProperty { get; set; }
}

这篇关于为什么需要使用get和set?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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