2014-03-02 36 views
3

有人可以解釋爲什麼鑄造對象無法使用隱式轉換運算符嗎?隱式轉換運算符似乎在裝箱之前使用,但一旦裝箱就失敗了。C#轉換運算符不知道被轉換爲對象?

class Program 
{ 
    static void Main(string[] args) 
    { 
     var ms = new MemoryStream(); 
     var wrapper = new GenericWrapper<MemoryStream> { Item = ms }; 

     object obj = wrapper; 
     object objMs = ms; 

     MemoryStream passingImplicitCast = (MemoryStream)wrapper; 

     MemoryStream passingCast = (MemoryStream)objMs; 
     MemoryStream failingCast = (MemoryStream)obj; //Throws Unable to cast object 
    } 
} 

class GenericWrapper<T> 
{ 
    public T Item { get; set; } 

    public static implicit operator T(GenericWrapper<T> value) 
    { 
     return value.Item; 
    } 
} 
+0

這也不是關於拳擊,而是關於鑄造。 – Dirk

+0

@Dirk yep,thx更新了 – deepee1

+0

我已經回答了一個相關問題[here](http://stackoverflow.com/a/18953867/2530848)。這應該有助於 –

回答

0

好了,有了這條線測試:

MemoryStream failingCast = (GenericWrapper<MemoryStream>)obj; 

最終, 「failingCast」 是一個System.IO.MemoryStream

enter image description here

由於obj是你需要更具體的一個object,並設置GenericWrapper<MemoryStream>。你需要返回值T

0

你不能超越型鑄造objGenericWrapper<MemoryStream>,因爲:

  1. object不知道如何將其自身轉換爲MemoryStream
  2. obj原本一個GenericWrapper<MemoryStream>

你唯一的選擇是投objGenericWrapper<MemoryStream>

MemoryStream failingCast = (MemoryStream)(GenericWrapper<MemoryStream>)obj; 

,並讓它鍵入式澆鑄GenericWrapper<MemoryStream>,現在知道如何將其隱式轉換自輸入MemoryStream因爲GenericWrapper<MemoryStream>有隱含的操作定義。

+0

你是對的,但這不是唯一的選擇。您可以使用動態並將責任推送到CLR,這將會很小心 –