雖然肯定是有在條款有些混亂您正在使用(我會讓別人解決這個問題),我想我明白你在說什麼,你是基本上是正確的。
特別是,它聽起來像你的同事認爲,這種情況正在發生:
// Now there is this "SomeFoo" object somewhere in memory.
SomeFoo fooClassInstance = new SomeFoo("test");
// Now there is this "IFoo" object somewhere in memory.
IFoo fooInterface = (IFoo)fooClassInstance;
// Let's say down the road somewhere, fooClassInstance is set to null or a different
// object. Your coworker believes that the object it originally pointed to will then
// have no references to it and will thus be eligible for garbage collection?
如果上面是你的同事的想法準確地表述,那麼你的同事是錯誤的,你是對的。 fooInterface
變量包含對fooClassInstance
有參考的同一對象的引用。您可以輕鬆簡單地通過執行以下操作進行驗證:
SomeFoo fooClassInstance = new SomeFoo("test");
IFoo fooInterface = (IFoo)fooClassInstance;
bool sameObject = ReferenceEquals(fooClassInstance, fooInterface);
如果ReferenceEquals
回報true
,那麼這兩個變量引用內存中的同一個對象。
如果你的同事需要進一步說服,試圖顯示他/她是這樣的:
List<int> list = new List<int> { 1, 2, 3 };
// This cast is actually not needed; I'm just including it so that it mirrors
// your example code.
IList<int> ilist = (IList<int>)list;
// Now we remove an item from the List<int> object referenced by list.
list.Remove(3);
// Is it in ilist? No--they are the same List<int> object.
Console.WriteLine(ilist.Contains(3));
// How about we remove an item using ilist, now?
ilist.Remove(2);
// Is it in list? Nope--same object.
Console.WriteLine(list.Contains(2));
// And here's one last thing to note: the type of a VARIABLE is not the same
// as the type of the OBJECT it references. ilist may be typed as IList<int>,
// but it points to an object that is truly a List<int>.
Console.WriteLine(ilist.GetType());
一個接口沒有實現,所以,是的,*實現*接口*的類可以*並且將超出範圍。一個接口就像一個合同 - 沒有任何實現只是你將實現什麼的承諾,因此沒有垃圾收集。在你的例子中,你創建了一個對原始對象的引用並將其轉換爲一個接口 - 這是COM中舊的IUnknown :: QueryInterface(雖然現在有很多不同 - 同樣的概念)。 – SRM 2011-01-27 21:18:44
在您的示例中,類和接口實例將同時超出作用域。 – Victor 2011-01-27 21:22:35
不需要將`fooClassInstance`強制轉換爲`IFoo`。它已經*是*`IFoo`。 – 2011-01-27 21:23:29