2011-08-15 42 views
6

所以我有一個泛型類(它主要是容器類)與隱式轉換,就像這樣:在運行時執行隱式轉換

public class Container<T> 
{ 
     public T Value { get; set; } 

     public static implicit operator T(Container<T> t) 
     { 
      return t.Value; 
     } 

     public static implicit operator Container<T>(T t) 
     { 
      return new Container<T>() { Value = t }; 
     } 
} 

所以在運行時,我想投的Container<int>實例使用爲int反射,但似乎無法找到一種方式,我已經嘗試了在幾個地方提到的「Cast」方法調用,但我得到一個Specified cast is not valid.異常。

任何幫助將不勝感激。

+1

那麼你知道什麼在編譯時和你知道不執行時間處理時間?你能給我們的調用代碼嗎? –

+0

您是否試圖將「Cast」容器轉換爲int或Container.Value? –

+1

你爲什麼不直接調用'Container.Value'? – jason

回答

4

這樣做幾乎沒有一個很好的理由,除非有問題的類型是不能修改的程序集內部的。

但是如果說到這一點,我個人更喜歡看起來更乾淨的dynamic解決方案(如jbtule所述)來反思。

不過既然你要求與反思的解決方案(也許你是在.NET 3.5或更早版本?),你可以這樣做:

object obj = new Container<int>(); 

var type = obj.GetType(); 
var conversionMethod = type.GetMethod("op_Implicit", new[] { type }); 
int value = (int)conversionMethod.Invoke(null, new[] { obj }); 
+0

謝謝,會給這個嘗試 –

1

通過使用dlr,可通過nuget中的開放源代碼ImpromptuInterface訪問,您可以動態地call an implicit or explicit cast

int intInstance =Impromptu.InvokeConvert(containerInstance, typeof(int)); 

雖然本實施例中是相當繁瑣的,並且可以通過

int intInstance = (dynamic) containerInstnace; 

來完成爲好。但如果你在編譯時不知道int Impromptu就是要走的路。

+0

謝謝,將調查 –

0

書寫隱式運算符允許您隱式地執行。換句話說,這是完全合法的:

int i = new Container<int>() { Value = 2 }; 
if (i == 2) 
{ 
    // This will be executed 
} 

如果你只有一個Container<object>那麼這是行不通的,但在這種情況下,你的代碼或許應該重構無論如何,因爲你基本上忽略了泛型參數你有。

+0

我不知道我明白你在這裏說什麼... –