c# - C#错误“方法名例外”我做错了什么
问题描述
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading;
namespace Exercise4
{
class MainClass
{
private char c;
public MainClass(char c)
{
this.c = c;
}
public void run()
{
while (true)
{
Console.WriteLine(c);
System.Threading.Thread.Sleep(1000);
}
}
public static void Main(string[] args)
{
Thread thA = new Thread(new ThreadStart(new MainClass('A'), run)); //Error Method Name Excepted : Error Code CS0149
Thread thB = new Thread(new ThreadStart(new MainClass('B'), run)); //Error Method Name Excepted : Error code CS0149
thA.Start();
thB.Start();
thA.Join();
thB.Join();
}
}
}
我是 C# 新手,我真的不明白那里有什么问题。
更准确地说,错误在这里:
new ThreadStart(new MainClass('A') , run )
new ThreadStart(new MainClass('B') , run )
此代码必须创建 5 个线程,每个线程显示一个字母“A”表示第一个,“B”表示第二个,依此类推。我尝试修改程序,以便每个线程在无限循环中显示其字母。
希望我能在那里得到一些帮助!
解决方案
您需要先初始化对象,然后可以将run
这些对象的方法传递给ThreadStart
:
public static void Main(string[] args)
{
var mainA = new MainClass('A');
var mainB = new MainClass('B');
Thread thA = new Thread(new ThreadStart(mainA.run));
Thread thB = new Thread(new ThreadStart(mainB.run));
...
后编辑:附加选项
如果您只需要两个初始化的对象来实现这一目的,您可以通过在同一行中处理初始化而不声明和设置其他变量来使这更加优雅:
Thread thA = new Thread(new ThreadStart(new MainClass('A').run));
Thread thB = new Thread(new ThreadStart(new MainClass('B').run));
推荐阅读
- android - 使用后退按钮退出应用程序后,我只能从共享偏好中获取值
- scheme - 什么是方案中的“字符串映射”?
- r - Dtedit Shiny R中的Depandant选择输入
- javascript - ecma262中的赋值表达式
- python - Python Crash Course - Project Alien Invasion - 第 13 章问题
- r - 提取第 n 次出现的两个符号之间的字符串
- javascript - 如何允许用户创建新页面并将其保存在服务器端?
- fastify - Fastify 模式无法验证嵌套对象的属性类型
- c++ - 如何修改此二叉搜索树 ADT 以实现优先队列 ADT?
- spring-boot - @ControllerAdvice 不抛出异常