2015-07-18 68 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; } 
    }   
相關問題