C# 不能通过实例引用访问;用类型名称来限定它

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13545346/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 08:57:55  来源:igfitidea点击:

cannot be accessed with an instance reference; qualify it with a type name instead

c#multithreading

提问by Jordan Trainor

Using Example 1: Creating, starting, and interacting between threadson this MSDN tutorialmore specificaly line 3 to line 7 in the Main()

使用示例 1:在此MSDN 教程中创建、启动和交互线程更具体地说是第 3 行到第 7 行Main()

I have the following code with the following error:

我有以下代码,但出现以下错误:

cannot be accessed with an instance reference; qualify it with a type name instead.

不能通过实例引用访问;用类型名称来限定它。

Program.cs

程序.cs

public static ThreadTest threadTest = new ThreadTest();
private static Thread testingThread = new Thread(new ThreadStart(threadTest.testThread()));
static void Main(string[] args)
{

}

ThreadTest.cs

线程测试.cs

public static void testThread()
{
}

采纳答案by Sergey Berezovskiy

Your testThreadis a static method, so it's available via type name. So, instead of using isntance threadTest, use ThreadTesttype.

testThread是一个静态方法,所以它可以通过类型名称使用。因此,不要使用 istance ,而是threadTest使用ThreadTest类型。

// public static void testThread()
testingThread = new Thread(new ThreadStart(ThreadTest.testThread));

Or change method declaration (remove static):

或更改方法声明(删除static):

// public void testThread()
testingThread = new Thread(new ThreadStart(threadTest.testThread));

Also you should pass method to delegate ThreadTest.testThread(parentheses removed) instead of passing result of method invokation ThreadTest.testThread().

此外,您应该将方法传递给委托ThreadTest.testThread(删除括号),而不是传递方法 invokation 的结果ThreadTest.testThread()