如何在当前对象中保留对另一个对象的引用

How to keep a reference to another object in current object

我知道可以通过使用 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 变为空!这怎么可能?

不可能完全按照您的要求进行操作,但是如果您使用 WrapperClass 包装 OtherClass 就可以实现该功能

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

这行不通,因为 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();
}

此时 invalidMakeRef 方法中引用了一个超出范围的局部变量。

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