One on the code, after explaining
usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingSystem.Text;namespaceteststatic{classProgram {Static voidMain (string[] args) {Console.WriteLine ("Resolve field initialization cannot reference non-static field issues"); A A=NewANewB ()); Console.WriteLine (A.restrs); //with the property call, you can resolve } } Public classA { PublicA (B obj) { This. str =obj; Console.WriteLine (str. Say2 ()); //The constructor can also be used to solve } PublicB Str {Get; Set; } //string a = str. Say2 (); //field initialization cannot reference non-static fields//Public String restrs = Restr ();//field initialization cannot reference non-static fields//and through the property call can be compiled through Public stringRestrs {Get { returnrestr (); } Set{restrs=value; } } Public stringrestr () {return "1 "can be solved by using the attribute call"; } } Public classB { PublicB () {} Public stringSay2 () {return "2 The use of constructors can also solve"; } }}
Second, field initialization cannot refer to non-static fields because:
1 C # syntax rule: Uninitialized variables are not allowed in C #.
2 Property memory and variable memory are allocated at different times. Attributes are allocated at the time of use, while variables are allocated at the time of class initialization.
3 "When you instantiate a class, because the static field assignment is already done in the static constructor, the instantiated field is instantiated in a non-static constructor, and the time before and after the static constructor is executed earlier than the non-static constructor, and for this reason, there are two problems:
1, when you assign a value to a static field with a non-static field, the field is always empty error
2, when you assign a non-static value to a class: field initialization cannot reference a non-static field
Third, the solution:
1 "We can put the corresponding code in the constructor of the class that currently needs to be assigned because of the problem caused by the order problem during initialization.
2 uses the property's get to assign a value, as in the example above
C # Variable initialization problem: field initializers cannot reference non-static fields, methods, or properties