8

以下是我的代码:

private BitsManager manager;
private const string DisplayName = "Test Job";       

public SyncHelper()
{
    manager = new BitsManager();
}        

BitsJob uploadBitsJob = manager.CreateJob(DisplayName, JobType.Upload);

我收到以下错误:

A field initializer cannot reference the non-static field, method, or property 'BITSIntegrationModule.SyncService.SyncHelper.manager'

4

2 回答 2

11

线

BitsJob uploadBitsJob = manager.CreateJob(DisplayName, JobType.Upload);

无法访问管理器,因为它尚未设置为任何内容 - 您可以将分配移动到构造函数中 -

private readonly BitsManager manager;
private const string DisplayName = "Test Job";       
BitsJob readonly uploadBitsJob;

public SyncHelper()
{
  manager = new BitsManager();
  uploadBitsJob = manager.CreateJob(DisplayName, JobType.Upload);
}   
于 2013-03-04T15:01:20.400 回答
3

uploadBitsJob在类级别声明,使其成为一个字段。字段实例不能用于初始化其他字段。

相反,您可以声明该字段而不对其进行初始化:

BitsJob uploadBitsJob;

然后在构造函数中初始化字段:

public SyncHelper()
{
  manager = new BitsManager();
  uploadBitsJob = manager.CreateJob(DisplayName, JobType.Upload);//here.  Now manager is initialized
}  
于 2013-03-04T15:11:55.533 回答