在类中设置对象 [英] Setting object inside a class

查看:93
本文介绍了在类中设置对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下疑问。

有一个包含一堆成员的类,其中一个是另一个类的对象。

我正在创建访问器保护非对象成员的输入(例如,字符串),我想知道为对象成员做同样的事情是否有意义。



如果我做这样的事情:



I have the following doubt.
Having a class which contains a bunch of members, one of which is an object of another class.
I am creating accessors to protect the input to non-object members (like, for instance, strings) , and I am wondering if it makes sense to do the same for the object member.

If i do something like this :

public class MyClass {

     string       member1;
     AnotherClass member2;

     string       Member1 {  get; set;}
     AnotherClass Member2 {  get { return member2;}
                             set {  ......do some controls....
                                    member2 = .... }

}





据我所知(但我可能错了),无论我在Member2.set做什么方法,

如果我使用Member2.get,我得到私有member2对象的引用,并且通过这个,我可以绕过在Member2.set访问器中进行的控制。或者是否有一些隐藏的控制机制阻止我以这种方式使用引用,一旦我将member2引用声明为私有?



我是什么尝试过:



在网站上找不到答案



As far as I know (but I maybe wrong) , no matter what I do in the Member2.set method ,
if I use the Member2.get , I get a reference to the private member2 object, and with this , I could bypass the controls made in Member2.set accessor . Or is there some hidden control mechanism that prevents me from using the reference in such a way, once I have declared the member2 reference as private ?

What I have tried:

looked unsuccessfully into the site for an answer

推荐答案

Nope,如果你返回引用,它就是引用,调用者可以用它做任何他喜欢的事情。



如果你想限制访问它的内部,你需要完全封装它,并提供属性和/或方法,只显示您希望调用者访问的那些功能。



请明确指定您的访问权限。

Nope, if you return the reference, it is the reference and the caller can do anything he likes with it.

If you want to restrict access to it's internals, you need to fully encapsulate it, and provide properties and / or methods to expose only those features you want teh caller to access.

And please, specify your access explicitly!
public class MyClass {
 
     private string       member1;
     private AnotherClass member2;
 
     public string       Member1 {  get; set;}
     public AnotherClass Member2 {  get { return member2;}
                                    set {  ......do some controls....
                                          member2 = .... }
}


这篇关于在类中设置对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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