简体   繁体   English

非静态方法需要目标C#

[英]Non-static method requires a target C#

I have a win form app with a listbox displaying methods (by attribute). 我有一个win表单应用程序,其中列表框显示方法(按属性)。 I am attempting to dynamically invoke methods in a thread, using reflection to get method info from the selected value of the the list box. 我试图动态调用线程中的方法,使用反射从列表框的选定值获取方法信息。 However, when calling Methodinfo.Invoke I am getting this inner exception "Non-static method requires a target C#". 但是,当调用Methodinfo.Invoke时,我得到了这个内部异常“非静态方法需要一个目标C#”。

Here's my code (keep in mind I'm still new to c# and programming in general.) 这是我的代码(请记住,我仍然是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 the method.

    if (testListBox.InvokeRequired)
        testListBox.BeginInvoke(new DelegateForTest(functionForTestListBox));
    else
        functionForTestListBox();

}

public void functionForTestListBox()
{
    _t = testListBox.SelectedIndex;

    if (_t < 0)
        return;

    _v = testListBox.SelectedValue;

    method = _v as MethodInfo;


    if (method == null)
        return;

    _selectedMethod = method.Name;

    MessageBox.Show(_selectedMethod.ToString());

    method.Invoke(null, null);//<----Not sure about this. it runs fine when I dont invoke in a thread.

    counter++;

}
private void runTestButton_Click(object sender, EventArgs e)
{// Click event that calls the selected method in the thread
    if (_serverStatus == "Running")
    {

        if (_testStatus == "Not Running")
        {

            // create Instance new Thread and add function
            // which will do some work
            try
            {
                SetupTestEnv();
                //functionForOutputTextBox();
                Thread UIthread = new Thread(new ThreadStart(GetTest));
                UIthread.Name = "UIThread";
                UIthread.Start();
                // Update test status
                _testStatus = "Running";
                //Make thread global
                _UIthread = UIthread;
            }
            catch
            {
                    MessageBox.Show("There was an error at during the test setup(Note: You must install each web browser on your local machine before attempting to test on them).");
            }

        }
        else
        {
            MessageBox.Show("Please stop the current test before attempt to start a new one");
        }
    }
    else
    {
        MessageBox.Show("Please make sure the server is running");
    }
}

You are trying to invoke non-static method without providing object instance reference, for which this method should be invoked. 您试图在不提供对象实例引用的情况下调用非静态方法,应该为此方法调用此方法。 Since you are working with methods of MainForm class, you should provide object of MainForm type in the first parameter of MethodInfo.Invoke(Object, Object[]) , in your case: 由于您正在使用MainForm类的方法,因此您应该在MethodInfo.Invoke(Object, Object[])的第一个参数中提供MainForm类型的MethodInfo.Invoke(Object, Object[]) ,在您的情况下:

if(method.IsStatic)
    method.Invoke(null, null);
else
    method.Invoke(this, null);

Example of executing method on separate thread: 在单独的线程上执行方法的示例:

public MethodInfo GetSelectedMethod()
{
    var index = testListBox.SelectedIndex;
    if (index < 0) return;
    var value = testListBox.SelectedValue;
    return value as MethodInfo;
}

private void ThreadProc(object arg)
{
    var method = (MethodInfo)arg;
    if(method.IsStatic)
        method.Invoke(null, null)
    else
        method.Invoke(this, null);
}

private void RunThread()
{
    var method = GetSelectedMethod();
    if(method == null) return;
    var thread = new Thread(ThreadProc)
    {
        Name = "UIThread",
    };
    thread.Start(method);
}

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

相关问题 EF非静态方法需要目标 - EF Non-static method requires a target 非静态方法需要一个目标 - Non-static method requires a target 邮递员为什么返回“非静态方法需要目标”。 - Why the postman is returning a “Non-static method requires a target.” 非静态方法需要PropertyInfo.SetValue中的目标 - Non-static method requires a target in PropertyInfo.SetValue 非静态方法在连接两个表时需要一个目标 - Non-static method requires a target at the time of joining two tables C#查询 - 非静态方法需要目标 - C# Query - Non Static Method Requires a Target 获取错误“静态方法需要空实例,非静态方法需要非空实例。” 尝试在 C# 中执行表达式树时 - Getting error “Static method requires null instance, non-static method requires non-null instance.” while trying to execute expression tree in C# 非静态方法需要目标 - Non static method requires a target System.Reflection.TargetException:&#39;非静态方法需要目标。 仅适用于VS 2017而不适用于VS 2013 - System.Reflection.TargetException: 'Non-static method requires a target.' only with VS 2017 not with VS 2013 收到错误消息:System.Reflection.TargetException:非静态方法需要一个目标 - Receiving error message: System.Reflection.TargetException: Non-static method requires a target
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM