C# 字段初始值设定项不能引用非静态字段、方法或属性

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15204420/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 14:28:03  来源:igfitidea点击:

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

c#microsoft-bitsbits-service

提问by Madurika Welivita

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'

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

采纳答案by NDJ

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);
}   

回答by Russki

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

这通常发生在尝试从静态方法访问非静态属性时。请提供更多代码。

回答by P.Brian.Mackey

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

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

Instead, you can declare the field without initializing it:

相反,您可以在不初始化的情况下声明该字段:

BitsJob uploadBitsJob;

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
}