[英]Using reflection call a method through property
在下面的代碼中,如何使用反射來調用“ MyMethod”。
我有一個現有的C#代碼,它具有預定義的結構,不允許更改。 我需要使用反射調用存在於類中的方法。
在下面的代碼中,“ _ instance”包含“ Foo”的對象。 我需要使用Consumer類中的“ PropElementHighlighter”屬性來調用“ MyMethod”。
使用System.Reflection;
public class Foo
{
public void MyMethod(string Argument)
{
//some code
}
}
public class MainWindow
{
private Foo _instance;
public Foo PropElementHighlighter { get { return _instance; } }
}
public class Consumer
{
Type control = MainWindow.GetType();
PropertyInfo l_propInfo = control.GetProperty("PropElementHighlighter", System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance);
MethodInfo l_HighlightMethodInfo = l_propInfo.PropertyType.GetMethod("MyMethod");
l_HighlightMethodInfo.Invoke(l_propInfo, new object[]{"Parameter1"});
}
我收到錯誤消息“對象與目標類型不匹配”。 同時調用方法。
由於在方法對象中設置屬性信息,因此出現錯誤。 嘗試設置屬性值:
Type control = mainWindow.GetType();
PropertyInfo l_propInfo = control.GetProperty("PropElementHighlighter", System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance);
var propertyValue = l_propInfo.GetValue(mainWindow);
MethodInfo l_HighlightMethodInfo = l_propInfo.PropertyType.GetMethod("MyMethod");
l_HighlightMethodInfo.Invoke(propertyValue, new object[] { "Parameter1" });
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.