A field initializer cannot reference the non-static field, method, or property

随声附和 提交于 2019-11-27 03:27:12

问题


Following is my code :

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

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

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

I am getting following error :

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


回答1:


The line

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

can't access manager because it hasn't been set to anything yet - you could move the allocation into the constructor -

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

public SyncHelper()
{
  manager = new BitsManager();
  uploadBitsJob = manager.CreateJob(DisplayName, JobType.Upload);
}   



回答2:


uploadBitsJob is declared at the class level which makes it a field. Field instances can't be used to initialize other fields.

Instead, you can declare the field without initializing it:

BitsJob uploadBitsJob;

Then initialize the field in the constructor:

public SyncHelper()
{
  manager = new BitsManager();
  uploadBitsJob = manager.CreateJob(DisplayName, JobType.Upload);//here.  Now manager is initialized
}  



回答3:


That usually happens when trying to access non-static property from static method. Please provide a bit more code.



来源:https://stackoverflow.com/questions/15204420/a-field-initializer-cannot-reference-the-non-static-field-method-or-property

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!