【问题标题】:How to keep a reference to another object in current object如何在当前对象中保留对另一个对象的引用
【发布时间】:2025-08-27 09:25:02
【问题描述】:

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

【问题讨论】:

  • 有时全局变量对于缓解压力非常有用.....(开玩笑的,我不认为这是可能的,让我们看看是否有人能治愈)
  • 这是不可能的,你必须有某种事件系统,或者在任何地方使用这个类的属性来实现这一点。
  • 这就是事件的用途。您的班级可以在 input 更改的任何时候引发事件,并且任何其他需要了解 input 更改的班级都可以订阅该事件。

标签: c# reference parameter-passing pass-by-reference


【解决方案1】:

不可能完全按照您的要求做,但是如果您使用 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;
        }
    }

【讨论】:

  • 感谢您的回答。这很有帮助。但是_wrapper.Input= null;_wrapper= null; 有什么区别呢?第一个是全局的,第二个是本地的。为什么?
  • 想想参考,比如打印页面,说明如何去某个地址。如果你和我有一份印有相同地址“A”的副本,我们都会来到同一个地方A,但你还是看一页,我看另一页。现在认为有人可以从您的页面中删除地址并在那里写下其他地址:“B”。因此,现在如果您按照页面上的指示,您将来到地址 B,而我仍然来到地址 A。将 null 设置为引用就像从您的页面中删除地址,所以您有空页面。我仍然有地址为 A 的页面。
  • 在我提出的解决方案中是对具有对实际类的引用的对象 WrapperClass 的引用:OtherClass。就像即使我们有页面,你也永远不会从页面中删除地址,所以我们总是有相同的地址,然后当我们都去同一个地址 A 时,我们都会找到另一个指向下一个地址的页面。如果有人删除了这个页面,那么我们都来到地址 A,找到这个页面并看到它是空的(null)。我希望这个类比没问题。
【解决方案2】:

这不起作用,因为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 方法内的一个局部变量,该变量超出了范围。

【讨论】:

    【解决方案3】:
      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; } 
       }          
    

    【讨论】:

      最近更新 更多