繁体   English   中英

C#MethodInfo调用

[英]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.'

你应该:

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

Invoke的第一个参数是您要调用方法/属性的对象的实例。因此,需要首先检索该属性的值。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM