首页 > 解决方案 > 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”表示第二个,依此类推。我尝试修改程序,以便每个线程在无限循环中显示其字母。

希望我能在那里得到一些帮助!

标签: c#

解决方案


您需要先初始化对象,然后可以将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));

推荐阅读