加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 不能使用非静态方法的线程

发布时间:2020-12-15 23:32:54 所属栏目:百科 来源:网络整理
导读:我试图从一个线程调用一个名为UpdateResults()的非静态方法.这是我的代码: class Live { Thread scheduler = new Thread(UpdateResults); public Live() { scheduler.Start(); } public void UpdateResults() { //do some stuff }} 但我得到这个错误: A fi
我试图从一个线程调用一个名为UpdateResults()的非静态方法.这是我的代码:

class Live
 {
     Thread scheduler = new Thread(UpdateResults);

     public Live()
     { 
         scheduler.Start();
     }

     public void UpdateResults() 
     {
        //do some stuff
     }
}

但我得到这个错误:

A field initializer can not refer to the property,method or non-static field ‘Live.UpdateResults ()’

我怎样才能解决这个问题?

解决方法

这与Thread无关.有关为何发生这种情况的详细信息,请参阅 this问题.
要解决您的问题,请按以下方式更改您的课程:

class Live
{
    Thread scheduler;

    public Live()
    { 
        scheduler = new Thread(UpdateResults);
        scheduler.Start();
    }

    public void UpdateResults() 
    {
       //do some stuff
    }
}

正如Jon Skeet在上述问题中提到的,从C#4规范的10.5.5.2节:

A variable initializer for an instance field cannot reference the
instance being created. Thus it is a compile-time error to reference
this in a variable initializer,because it is a compile-time error for
a variable initializer to reference any instance member through a
simple-name.

当您编写新的Thread(UpdateResults)时,您实际上正在编写新的Thread(this.UpdateResults).

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读