当我将它作为参数传递给方法时,如何修改相同的变量?

时间:2015-02-03 11:04:41

标签: c#

好吧,我必须上课,ClassA是主类,ClassB是辅助类。代码就是这个。

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;
    }
}

好吧,我的想法是当我在ClassB上将变量_myCustomObject设置为null时,在ClassA中myCustomObject将为null。但我知道在这种情况下代码不起作用,因为在ClassB中我修改了一个与classA上变量引用不同的引用。

我的想法是修改相同的引用,因为我想在使用MVVM模式的应用程序中创建一个对话框,我想使用CustomObject作为通信变量,作为对话框的结果。

非常感谢。

1 个答案:

答案 0 :(得分:2)

试试这个:

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;
    }
}