简体   繁体   中英

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

Ok so I have the code below, technically all it does is read the db.txt file line by line and then its suppose to split the line 0 into an array called password.

private string[] lines = System.IO.File.ReadAllLines(@"U:\Final Projects\Bank\ATM\db.txt");
private string[] password = lines[0].Split(' ');

but I get the error:

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

Have a think about what the above means and how you want to populate those variables. You'd need to first construct the class they are a member of, and then hope the lines of code get executed in the order you want them to, and that they don't throw an exception.

The compiler is effectively telling you this isn't the right way to do things.

A better way is to simply write a function to do what you want:

private string[] PasswordLines(){
  string[] lines = System.IO.File.ReadAllLines(@"U:\Final Projects\Bank\ATM\db.txt");
  return lines[0].Split(" "); 
}

You can then call this from anywhere you wanted to; for example:

public class MyClass()
{
 private string[] Lines 
 {
   get { return PasswordLines(); }
 }

 private string[] PasswordLines(){
  string[] lines = System.IO.File.ReadAllLines(@"U:\Final Projects\Bank\ATM\db.txt");
  return lines[0].Split(" "); 
 }

}

C# does not guarantees any specific order of execution when it comes to filed initialization.
For instance these two lines of code will produce undefined results:

private int a = b + 1;
private int b = a + 1;

in theory, the two possible outcomes are a=1,b=2 or a=2,b=1, but in fact it's even worst. We don't even know if a and b are initialized to their default values yet (0 in case of int), so it can be anything (just like a reference to uninitialized object). To avoid this impossible-to-solve scenario, the compiler demands that all field initializations will be "run-time constants" (return the same value every time, whenever they are executed and independent of any other non "run-time constant" variables).

Just use the constructor when you initialize compound fields and life will be sweet again.

Exactly what is says! Those are (instance) field initializers, and cannot reference each other. Move the code to the constructor instead, or make them method variables instead of fields.

The error is self explanatory.

you can't do this because lines and password both are field variables and you can't assign

one of them value to other(if it's a static then you can).

i hope you are using this code inside a class so until unless an object is not create their no such real existence of these field variables so you can't assign them to each other.

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