2012-07-18 89 views
21

我有一個類Thing可以從string隱式轉換。當我直接調用Thing參數的方法時,從stringThing的投射正確完成。如何隱式投射反射方法調用

但是如果我使用反射來稱呼它拋出異常

System.ArgumentException : Object of type 'System.String' cannot be 
converted to type 'Things.Program+Thing'. 

也許有這個一個很好的理由同樣的方法,但我無法弄清楚。有人有一個想法如何使用反射得到這個工作嗎?

namespace Things 
{ 
    class Program 
    { 
     public class Thing 
     { 
      public string Some; 

      public static implicit operator Thing(string s) 
      { 
       return new Thing {Some = s}; 
      } 
     } 

     public void showThing(Thing t) 
     { 
      Console.WriteLine("Some = " + t.Some); 
     } 

     public void Main() 
     { 
      showThing("foo"); 
      MethodInfo showThingReflected = GetType().GetMethod("showThing"); 
      showThingReflected.Invoke(this, new dynamic[] {"foo"}); 
     } 
    } 
} 

Meta:請不要討論爲什麼隱式投射或反射不好。

+4

關於我的頭頂,我會打賭是因爲(我認爲,並糾正我,如果我錯了),隱式轉換是編譯器的語法糖。在編譯時實際調用鑄造方法。編輯:你需要有一些通用的方式來調用隱式轉換器的任何對象轉換?或者這是一種特殊情況,你會願意將一個單獨的靜態方法或其他反射調用指定給一個預定義的方法或一個專門的構造函數? – 2012-07-18 14:48:53

+0

類似的問題[這裏](http://stackoverflow.com/questions/4501469/c-sharp-implicit-cast-overloading-and-reflection-problem) – 2012-07-18 14:54:27

+2

隱式轉換是不可能通過反射,但你可以使用[TypeConvertor]( http://msdn.microsoft.com/en-us/library/98bbex99.aspx#the_typeconverter_class)。 – 2012-07-18 14:58:49

回答

1

在這種特定的情況下,你可以通過數組類型進行轉換,即

showThingReflected.Invoke(this, new Thing[] {"foo"}); 

但那是一種「欺騙」的。一般來說,你不能指望Invoke考慮你的用戶定義的implicit operator。此轉換必須在編譯時推斷。

9

關鍵是要認識到,編譯器創建你的隱式轉換操作符稱爲op_Implicit一種特殊的靜態方法。

object arg = "foo"; 

// Program.showThing(Thing t) 
var showThingReflected = GetType().GetMethod("showThing"); 

// typeof(Thing) 
var paramType = showThingReflected.GetParameters() 
            .Single() 
            .ParameterType; 

// Thing.implicit operator Thing(string s) 
var converter = paramType.GetMethod("op_Implicit", new[] { arg.GetType() }); 

if (converter != null) 
    arg = converter.Invoke(null, new[] { arg }); // Converter exists: arg = (Thing)"foo"; 

// showThing(arg) 
showThingReflected.Invoke(this, new[] { arg }); 
+0

精彩!!!!!!!!!!!!! – denfromufa 2016-09-20 05:55:50

+0

這裏是另一個類似的答案:http://stackoverflow.com/a/32025393/2230844 – denfromufa 2016-09-20 06:00:15