我有一个win表单应用程序,其中列表框显示方法(按属性).我试图动态调用线程中的方法,使用反射从列表框的选定值获取方法信息.但是,当调用Methodinfo.Invoke时,我得到了这个内部异常"非静态方法需要一个目标C#".
这是我的代码(请记住,我仍然是c#和编程的新手.)
private void PopulateComboBox()
{//Populates list box by getting methods with declared attributes
MethodInfo[] methods = typeof(MainForm).GetMethods();
MyToken token = null;
List<KeyValuePair<String, MethodInfo>> items =
new List<KeyValuePair<string, MethodInfo>>();
foreach (MethodInfo method in methods)
{
token = Attribute.GetCustomAttribute(method,
typeof(MyToken), false) as MyToken;
if (token == null)
continue;
items.Add(new KeyValuePair<String, MethodInfo>(
token.DisplayName, method));
}
testListBox.DataSource = items;
testListBox.DisplayMember = "Key";
testListBox.ValueMember = "Value";
}
public void GetTest()
{//The next two methods handle selected value of the listbox and invoke …Run Code Online (Sandbox Code Playgroud) 让我们假设,我们有以下三种类型:
class class1{ public static int serial=1};
class class2{ public static int serial=2};
class class3{ public static int serial=3};
Run Code Online (Sandbox Code Playgroud)
序列可以是静态字段或属性,如:
class class1{ public override byte serial {get{return 0x01; }}};
Run Code Online (Sandbox Code Playgroud)
在我的应用程序中,我从某处收到序列值,需要反映相应的类.是否可以使用该项目的序列字段反映任何这些类型?我是否必须在序列ID和类名之间创建一个映射表来查找反射的相关类名?或System.Reflection允许我直接从其字段或属性值中找到类?我认为这将是一种更好的方法,因为我们不需要为新类型编辑表格.
谢谢你的帮助.