Reference to an object is not updating the object

前端 未结 3 1746
旧巷少年郎
旧巷少年郎 2021-01-29 14:38

Hi I am working with code that looks something like this .

class A
{
    Custom objA;

    public A()
    {
        //Assign some value to objA;
        B obj =          


        
3条回答
  •  长发绾君心
    2021-01-29 15:20

    In function Func you assign null to the field of B object (not A object) so after this function call field objB of B object is not pointing to any object of type Custom, but objA field of A object is still pointing to a single Custom object.

    Here is example of code, where Func will change objA field of A object:

    class A
    {
        public Custom objA = new Custom();
    
        public A()
        {
            B obj = new B(this);
            B.Func(); // after this, objA field will be null
        }
    }
    
    class B
    {
        А obj;
    
        public B(А obj)
        {
            this.obj = obj;
        }
    
        public void Func()
        {
            obj.objA = null;
        }
    }
    

    Also note:

    1. When you create an A object, its objA field is null, so in constructor of A you actually calling B obj = new B(null);, so its objB field is null too.
    2. After A object is constructed, object obj of type B will be disposed, since you don't hold a reference to it, so you not calling a Func function in your example.

提交回复
热议问题