非静态方法需要一个目标C# [英] Non-static method requires a target C#

查看:2625
本文介绍了非静态方法需要一个目标C#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个列表框显示方式(按属性)一个双赢的形式应用。我试图动态调用线程中的方法,使用反射来获取从列表框中选定值方法的信息。然而,当调用的 Methodinfo.Invoke 的我得到这个内部异常非静态方法需要一个目标C#。



下面是我的代码(记住我还是新的C#和一般节目。)

 私人无效PopulateComboBox()
{//通过让与声明的属性
的MethodInfo [] =方法typeof运算(的MainForm).GetMethods方法填充列表框();

即为MyToken令牌= NULL;
名单,LT; KeyValuePair<弦乐,MethodInfo的>>项目=
新的List< KeyValuePair<字符串,MethodInfo的>>();

的foreach(在方法MethodInfo的方法)
{
标记= Attribute.GetCustomAttribute(方法,
typeof运算(即为MyToken),FALSE)作为即为MyToken;
如果(令牌== NULL)
继续;

items.Add(新KeyValuePair<弦乐,MethodInfo的>(
token.DisplayName,法));

}

testListBox.DataSource =物品;
testListBox.DisplayMember =键;
testListBox.ValueMember =值;
}

公共无效GetTest()
{ListBox的//接下来的两个方法手柄值选择并调用该方法。

如果(testListBox.InvokeRequired)
testListBox.BeginInvoke(新DelegateForTest(functionForTestListBox));
,否则
functionForTestListBox();

}

公共无效functionForTestListBox()
{
_t = testListBox.SelectedIndex;

如果(_T℃下)
的回报;

_V = testListBox.SelectedValue;

法= _V为MethodInfo的;


如果(方法== NULL)
的回报;

_selectedMethod = method.Name;

MessageBox.Show(_selectedMethod.ToString());

method.Invoke(NULL,NULL); //< ----不知道这件事。当我不在一个线程调用运行正常。

计数器++;

}
私人无效runTestButton_Click(对象发件人,EventArgs五)
{// Click事件,在线程
调用所选的方法,如果(_serverStatus ==暗战)
{

如果(_testStatus ==未运行)
{

//创建实例新线程并添加功能
//这将做一些工作

{
SetupTestEnv();
// functionForOutputTextBox();
螺纹UIthread =新主题(新的ThreadStart(GetTest));
UIthread.Name =UIThread;
UIthread.Start();
//更新测试状态
_testStatus =运行;
//定义线程全球
_UIthread = UIthread;
}

{
MessageBox.Show(有在测试设置(在一个错误注意:您必须尝试测试前,在本地计算机上安装的每个Web浏览器在他们)。);
}

}
,否则
{
MessageBox.Show(请停止当前测试之前尝试启动一个新的);
}
}
,否则
{
MessageBox.Show(请确保服务器运行);
}
}


解决方案

您试图调用非静态方法不提供对象实例参考,此方法应被调用。既然你是用 MainForm的方法工作,你应该提供的MainForm 的对象类型<$的第一个参数C $ C> MethodInfo.Invoke(对象,对象[]),你的情况:

 如果(method.IsStatic)
method.Invoke(NULL,NULL);
,否则
method.Invoke(本,NULL);

在单独的线程中执行的方法的例子:

 公共MethodInfo的GetSelectedMethod()
{
VAR指数= testListBox.SelectedIndex;
如果(指数℃的)回报;
VAR值= testListBox.SelectedValue;
返回值MethodInfo的;
}

私人无效ThreadProc的(对象ARG)
{
VAR方法=(MethodInfo的)ARG;
如果(method.IsStatic)
method.Invoke(NULL,NULL)
,否则
method.Invoke(本,NULL);
}

私人无效RunThread()
{
VAR方法= GetSelectedMethod();
如果(方法== NULL)回报;
变种线程=新主题(ThreadProc的)
{
NAME =UIThread,
};
thread.Start(法);
}


I have a win form app with a listbox displaying methods (by attribute). 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#".

Here's my code (keep in mind I'm still new to c# and programming in general.)

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:

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);
}

这篇关于非静态方法需要一个目标C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆