C# 如何创建新对象并更改其他引用
如何在不丢失X对Y的引用的情况下执行此操作C# 如何创建新对象并更改其他引用,c#,C#,如何在不丢失X对Y的引用的情况下执行此操作 public class Test { public void Main() { AbstractClass X = new Foo(); Test2 test2 = new Test2(X); X = new Bar(); // I need to change Y as
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
{ }
我不确定你想达到什么目的,但我想你是想让这种情况发生的:
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 :( ");
}
你不能。如果您需要类似的东西,您可以将
抽象类
包装在另一个类中,并将其作为引用传递
以下是您的做法:
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 :( ");
}
请明确说明你想做什么:根本不清楚。基本上,你不能t@Selman22是的,但他想知道如何做到这一点,以另一种方式,在不丢失X和Y的引用的情况下。@Guilleira,答案是:你不能。对于这样一个模糊的问题,很难找到合适的解决办法。@GolezTrol vague?我可以看到这里回答了两个解决方法…谢谢你的回答。