为什么要使用getter和setter方法设置类属性? [英] Why to use getter and setter methods to set class properties?

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

问题描述

可能重复:
为什么要使用getter和setter?

在C#(ASP.NET)中,我们使用getter和setter方法来设置私有变量的属性,但是如果我们将该变量声明为public,则可以完成相同的操作.因为一方面,我们通过将变量声明为私有来限制用户访问该变量,另一方面,我们允许用户使用getter和setter属性来访问这些属性.我不明白它的意义.

In C#(ASP.NET) we use getter and setter methods to set properties of private variables but same thing can be done if we declare that variable as public. Because at one end we are restricting user from accessing that variable by declaring it as private and on other end we are allowing user to access those properties by using getter and setter properties. I can't understand its significance.

推荐答案

使用getter和setter可以隐藏类的内部实现.这意味着在设置器的set方法中,您可以运行整个算法以将输入数据解析为内部数据结构.您以后可以更改实现,而对用户没有任何影响.

by using getter and setter you hide the internal implementation of your class. which means in the set method of a setter, you can run a whole algorithm to parse the input data into your internal data structure. you'll be able to later change your implementation without any impact to your users.

现在,如果您将内部成员公开,则不能再将其隐藏,并且您对类内部定义所做的任何更改都可能会破坏用户的使用.

now if you expose your internal members as public, you can't hide them anymore, and any change you make to your class internal definition will probably break the user usage.

这篇关于为什么要使用getter和setter方法设置类属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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