C#MethodInfo调用

时间:2017-04-06 09:48:38

标签: c# reflection methodinfo

我在这段代码中找不到问题。我正在尝试找到一种特殊的属性并在其上调用一个方法。

该功能如下:

prevCall

例外情况如下:

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;
}

1 个答案:

答案 0 :(得分:1)

你应该:

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

Invoke的第一个参数是你想要调用方法/属性的对象的实例......所以需要先检索属性的值。