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

问题描述

我有以下疑问。

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

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



如果我做这样的事情:



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

推荐答案

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 = .... }
}


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

10-11 18:58