如何创建新对象并更改其他引用

时间:2014-03-27 11:43:21

标签: c#

如何在不丢失Y上的X引用的情况下执行此操作?

        public class Test
        {
            public void Main()
            {
                AbstractClass X = new Foo();

                Test2 test2 = new Test2(X);

                X = new Bar(); // I need to change Y as well.

                //Now, X is Bar, and Y is Foo. 
                if (X == test2.Y)
                    MessageBox.Show("They are equal! Success!!");
                else
                    MessageBox.Show("Not equal :( ");
            }
        }

        public class Test2
        {
            public AbstractClass Y { get; set; }

            public Test2(AbstractClass y)
            {
                Y = y;
            }
        }

        public abstract class AbstractClass
        { }

        public class Foo : AbstractClass
        { }

        public class Bar : AbstractClass
        { }

2 个答案:

答案 0 :(得分:3)

你不能。如果您需要类似的东西,可以将AbstractClass包装在另一个中并将其作为参考传递。

以下是你的去法:

public class MyPropertyStore
{
    public AbstractClass MyProperty {get;set;}
}

public class Test2
{      
    private MyPropertyStore propertyStore;
    public AbstractClass Y { get { return propertyStore.MyProperty ;} }

    public Test2(MyPropertyStore propertyStore)
    {
        this.propertyStore= propertyStore;
    }
}

public void Main()
{
    AbstractClass X = new Foo();
    MyPropertyStore store = new MyPropertyStore 
    {
     MyProperty  = X,
    };
    Test2 test2 = new Test2(store);

    store.MyProperty = new Bar(); // Now test2.Y will be pointing to same reference

    //Now, X is Bar, and Y is Foo. 
    if (X == test2.Y)
        MessageBox.Show("They are equal! Success!!");
    else
        MessageBox.Show("Not equal :( ");
}

答案 1 :(得分:1)

我不确定你想要实现什么,但我认为你想要发生这种情况:

public void Main()
{
    AbstractClass X = new Foo();

    Test2 test2 = new Test2(X);

    X = new Bar(); 

    // change test2.Y
    test2.Y = X;

    if (X == test2.Y)
        MessageBox.Show("They are equal! Success!!");
    else
        MessageBox.Show("Not equal :( ");
}