简体   繁体   中英

asp.net c# - A field initializer cannot reference the non-static field, method or property

I have the following code in my class:

    public string StrLog {get; set;}

then within the same class, I have the following code:

    private string imgData = StrLog;

I get the following error message:

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

It has a problem with:

    private string imgData = StrLog;

but not sure how to resolve this.

Basically, you cannot initialise a class level variable by using any other class level value (unless that value is static) - which is what your error is trying to tell you.

Your best option would be to assign the value in your constructor:

private string imgData = null;

public MyClass()
{
   imgData = "some value";
}

In your case there is no point assigning it the value of StrLog because StrLog won't have a value to begin with. So you may as well just assign it null , or an actual value form somewhere else (like my example)

You are not allowed to use a non-static memeber to intialize a member variable.

You need to intialize it first by setting it up in your constructor.

eg:

imgData = null;

I would strongly encourage you to assign something (something could be null) in the constructor. It's just good form. In the example below, you will see why it is important. What if a get is executed first and the value isn't set? It should at least contain a null value.

Having said that, if you want the value of imgData to be populated with the value of your public-facing property, you need to do the following:

public string StrLog
{
   get { return imgData; }
   set { imgData = value; }
}

This will pass the value of StrLog into imgData, with no work required on your part.

Make imgData your property , same way as Strlog. and then assign . it will work.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM