【问题标题】:C# method name expected, trying to parse a number through a function call应为 C# 方法名称,尝试通过函数调用解析数字
【发布时间】:2021-07-27 13:18:41
【问题描述】:

我试图调用一个函数“disp”并解析数字 1,但它有问题,说明方法名称是预期的。如果我能理解如何解析一个数字和 threadstart 中的函数,那就太棒了。提前谢谢你

    class Class1
    {
        public static void disp(int num)
        {

                try
                {
                    Console.WriteLine(num);
                    Thread.Sleep(500);
                }
                catch (Exception e)
                {
                    Console.WriteLine("ERROR");
                }

            Console.WriteLine("Done");


        }

        public static void Main(string[] args)
        {
            ThreadStart ts1 = new ThreadStart(disp(1));
            Thread t = new Thread(ts1);
            t.Start();
            Console.ReadLine();

        }
    }
}

【问题讨论】:

标签: c#


【解决方案1】:

根据ThreadStart Delegate:
要使用静态线程过程启动线程,请使用 类名方法名当你创建 ThreadStart 代表。从 .NET Framework 2.0 版开始, 没有必要显式地创建委托。 在 Thread 构造函数中指定方法的名称, 并且编译器会选择正确的委托。

using System;
using System.Threading;
                    
public class Program
{
    public static void disp(int num)
    {

        try
        {
            Console.WriteLine(num);
            Thread.Sleep(500);
        }
        catch (Exception e)
        {
            Console.WriteLine("ERROR");
        }

        Console.WriteLine("Done");
    }
    
    public static void disp1()
    {
        disp(1);
    }
    
    public static void Main()
    {
        ThreadStart ts1 = new ThreadStart(disp1);
        Thread t = new Thread(ts1);
        t.Start();

    }
}

dotnetfiddle

【讨论】:

    【解决方案2】:

    如果要将参数传递给静态方法,则需要使用 ParamaterizedThreadStart

    class Class1
    {
        public static void Disp(object num)
        {
    
                try
                {
                    Console.WriteLine((int)num);
                    Thread.Sleep(500);
                }
                catch (Exception e)
                {
                    Console.WriteLine("ERROR");
                }
    
            Console.WriteLine("Done");
    
    
        }
    
        public static void Main(string[] args)
        {
            Thread t = new Thread(Class1.Disp);
            t.Start(1);
            Console.ReadLine();
    
        }
    }
    

    }

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-12-03
      • 2011-04-03
      • 2015-04-30
      • 1970-01-01
      相关资源
      最近更新 更多