字段初始化项不能引用非静态字段、方法或属性
本文关键字:字段 方法 属性 静态 初始化 不能 引用 | 更新日期: 2023-09-27 18:02:02
我的代码如下:
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'
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);
}
uploadBitsJob
是在类级别声明的,这使得它成为一个字段。字段实例不能用于初始化其他字段。
相反,您可以声明该字段而不初始化它:
BitsJob uploadBitsJob;
然后初始化构造函数中的字段:
public SyncHelper()
{
manager = new BitsManager();
uploadBitsJob = manager.CreateJob(DisplayName, JobType.Upload);//here. Now manager is initialized
}