[英]C# MethodInfo Invoke
I can't find the problem in this code. 我在这段代码中找不到问题。 I'm trying to find a particular kind of property and invoke a method on it. 我试图找到一种特殊的属性,并在其上调用一个方法。
The function is the following: 该函数如下:
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;
}
And the exception is the following: 例外情况如下:
System.Reflection.TargetException: 'Object does not match target type.'
You should: 你应该:
object propValue = property.GetValue(root);
return m.Invoke(propValue, new object[] {Value1}) as string;
The first parameter of Invoke
is the instance of the object you want to call the method/property... So need to retrieve the value of the property first. Invoke
的第一个参数是您要调用方法/属性的对象的实例。因此,需要首先检索该属性的值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.