简体   繁体   中英

How can modify the same variable when I pass it as parameter on a method?

Well, I have to classes, ClassA is the main class and the ClassB is the auxiliar class. the code is this.

class ClassA
{
    private void myMthod()
    {
        MyClassB myClassB = new ClasB();
        CustomObject myCustomObject = new CustomObject();
        myClassB.MyMethodOnClassB(myCustomObject);

        if(miCustomObject == null)
        {
             //code in case of null
        }
        else
        {
            //code in case of not null
        }
    }
}


class ClassB
{
    CustomObject _myCustomObjectOnB;

    public ClassB(CustomObject paramCustomObject)
    {
        _myCustomObjectOnB = paramCustomObject;
    }

    public MyMethodOnClassB()
    {
        _myCustomObject = null;
    }
}

Well, the idea is that when I set to null the variable _myCustomObject on ClassB, in the ClassA myCustomObject would be null. But I know that in this case the code does not work because in the ClassB I am modify a reference different to the reference of the variable on the classA.

The idea is to modify the same reference, because I would like to create a dialog in an application that use the MVVM pattern and I would like to use CustomObject as communication variable, as result of the dialog.

Thank so much.

Try this:

class ClassA
{
    private void myMthod()
    {
        MyClassB myClassB = new ClasB();
        CustomObject myCustomObject = new CustomObject();
        myClassB.MyMethodOnClassB(ref myCustomObject);

        if(miCustomObject == null)
        {
             //code in case of null
        }
        else
        {
            //code in case of not null
        }
    }
}


class ClassB
{
    CustomObject _myCustomObjectOnB;

    public ClassB(CustomObject paramCustomObject)
    {
        _myCustomObjectOnB = paramCustomObject;
    }

    public MyMethodOnClassB(ref CustomObject customObject)
    {
        _myCustomObject = customObject = null;
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM