2016-04-28 23 views
3

我想从线程中调用一个名为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()'

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

回答

3

这与Thread无关。有关详细情况,请参阅this问题。 解决您的问题,改变你的类,如下所示:

class Live 
{ 
    Thread scheduler; 

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

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

由于乔恩斯基特提到了上述问题,从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.

当你写new Thread(UpdateResults)你真的在写new Thread(this.UpdateResults)

+0

只是一个问题:在'线程调度;'我得到'场 'LiveScore.scheduler' 分配,但它的价值是永远使用',只是一个警报。 – Dillinger

+1

因为您只在构造函数中使用私有字段。如果你不想在另一个方法中使用这个变量,那么你最好使它在构造函数中是局部的。当你从另一个方法引用变量时,错误将消失 –

4

C#6.0解决方案:改变分配(=)来初始化=>

class Live { 
    // Please, note => instead of = 
    Thread scheduler => new Thread(UpdateResults); 

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

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

这将有效地将它从字段更改为属性,因为=>仅是标准getter的语法糖 – Fabjan

+0

是一个lamba表达式,对不对? :) – Dillinger

+1

@Dillinger:*语法*是一个lambda,但实际上它是一种初始值设定项(在实例创建时赋值) –

相关问题