2017-04-06 10 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

ありがとうございました!それは完全に動作します。 –