2015-07-18 67 views
0

我知道通过使用ref关键字,可以在方法中引用另一个对象。在该方法内部的以下示例中创建的对象也可用于该方法之外。如何保留对当前对象中另一个对象的引用

public Method(ref OtherClass input) 
{ 
    input = new OtherClass(); 
} 

但我需要领先一步。我需要将引用作为属性保留在对象中,并且在将来需要其他方法时随时更改原始对象。

public class CLass1 
{ 
    OtherClass _input; 
    public Bind(ref OtherClass input) 
    { 
      input = new OtherClass(); // instantiating the object 
      _input = input; // keeping a reference of the created object for later usage! 
    } 
    public void Unbind() 
    { 
     _input = null; 
    } 
} 

当我Bind对象有一个新的对象初始化原始对象,这正是我想要的。但在此之后,我运行Unbind()只有_ input变为空,并且input保持不变。我需要的input也变为空!这怎么可能?

+1

有时全局变量是缓解压力的那么有用.....(开个玩笑,我不认为这是可能的,让我们来看看,如果有人有治愈) – Steve

+1

这是不可能的,因为这样,你会必须有某种事件系统,或者使用这个类的属性来实现这一点。 –

+1

请看这里http://stackoverflow.com/a/7253417/3888877 –

回答

1

这是不可能做的正是你所要求的东西,但你可以实现的功能,如果你有WrapperClass

public class WrapperClass 
{ 
    public OtherClass Input; 
} 


public class CLass1 
    { 
     WrapperClass _wrapper; 
     public Bind(ref WrapperClass wrapper) 
     { 
       wrapper = new WrapperClass(); 
       wrapper.Input = new OtherClass(); // instantiating the object 
       _wrapper = wrapper; // keeping a reference of the created object for later usage! 
     } 
     public void Unbind() 
     { 
      _wrapper.Input= null; 
     } 
    } 
+0

感谢你的答案。这很有帮助。但'_wrapper.Input = null;'和'_wrapper = null;'有什么区别?第一个是全球性的,第二个是本地的。为什么? –

+2

认为像打印页面的参考指示如何去一些地址。如果您和我的副本上印有相同的地址“A”,我们都会到同一个地方A,但您仍然可以看到一个页面,然后看另一个页面。现在认为有人可以从你的页面上删除地址,并在那里写下其他地址:“B”。所以,现在如果你按照你的网页上的指示,你会来到地址B,而我仍然来到地址A.把null引用就像从你的页面中删除地址,所以你有空的页面。我仍然有地址为A的页面。 –

+1

在我提出的解决方案中,引用了对象WrapperClass,它引用了实际的类:OtherClass。就好像我们有页面,你永远不会从你的页面中删除地址,所以我们总是有相同的地址,然后当我们都转到同一个地址A时,我们都会找到另一个页面,指向下一个地址。如果有人将此页面擦除,那么我们都来解决A,找到这个页面并且看到它是空的(空)。我希望这个比喻是可以的。 –

0

这样可不行换你OtherClass,因为ref是有意义的,只是作为一个方法的参数。除了方法范围之外,不能存储引用,因为您不知道通过引用传递给方法的变量的范围。例如,认为如果这样做会发生什么:

class WithRef { 
    // Imagine you can do this 
    public ref OtherClass other; 
    public WithRef(ref OtherClass other) { 
     this.other = other; 
    } 
} 

现在让我们说你这样做:

WithRef MakeRef() { 
    OtherObject variable; 
    return new WithRef(ref variable); 
} 
void Test() { 
    var invalid = MakeRef(); 
} 

此时invalid引用内部MakeRef方法的局部变量,这是超出范围。

0
public abstract class SelfRefType 
    <T extends< SelfRefType<T>> { 
     private OtherType<T>_ref; 
     protected abstract T getThis(); 
     public void set() { 
      _ref.m(getThis()); } 
    } 

    public interface OtherType<E> { 
      void m(E arg); 
    } 

    public Subtype extends 
     SellfRefType<Subtype> { 
     protected Subtype getThis() { 
     return this; } 
    }   
相关问题