以下是我的代码:
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'
答案 0 :(得分:10)
该行
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);
}
答案 1 :(得分:2)
uploadBitsJob
在类级别声明,使其成为一个字段。字段实例不能用于初始化其他字段。
相反,您可以在不初始化的情况下声明该字段:
BitsJob uploadBitsJob;
然后在构造函数中初始化字段:
public SyncHelper()
{
manager = new BitsManager();
uploadBitsJob = manager.CreateJob(DisplayName, JobType.Upload);//here. Now manager is initialized
}
答案 2 :(得分:-4)
尝试从静态方法访问非静态属性时通常会发生这种情况。请提供更多代码。