2017-04-06 31 views
0

我在這段代碼中找不到問題。我試圖找到一種特定類型的財產,並調用它的方法。C#MethodInfo Invoke

的功能如下:

private string GetLangTranslator(object root) 
{ 
    var properties = root.GetType().GetProperties(); 

    foreach (var property in properties) 
    { 
     if (typeof(MultiLanguage) == property.PropertyType) 
     {      
       MethodInfo m = property.PropertyType.GetMethod("Translate"); 

       return m.Invoke(property.PropertyType, new object[] {Value1}) as string;      
     } 
    } 

    return null; 
} 

而例外的是以下內容:

System.Reflection.TargetException: 'Object does not match target type.' 

回答

1

您應該:

object propValue = property.GetValue(root); 
return m.Invoke(propValue, new object[] {Value1}) as string; 

Invoke第一個參數是實例要調用方法/屬性的對象...因此需要檢索值物業第一。

+0

謝謝!它完美的作品。 –