简体   繁体   中英

A field initializer cannot reference the non-static field, method, or property in ASP.Net MVC Controller

I have a BaseController class inherited from MVC Controller-

public abstract class BaseController : Controller
{
    protected int A= Convert.ToInt32(ConfigurationManager.AppSettings["A"]);
    protected int B= Convert.ToInt32(ConfigurationManager.AppSettings["B"]);

    protected int C= A* B;
}

It gives error A field initializer cannot reference the non-static field, method, or property during compile.

I don't have any constructor. And that's full code of this class. Any help?

The error message relates to your attempt to assign C the value of A * B.

Try creating a protected contructor that carries out the assignment operation, ensure your sub classes then call this base constructor.

Since BaseController is an abstract class, you cannot create an instance of the class. So, you cannot call constructor of the abstract class. But you have to have a constructor to run the following code.

protected int C= A* B;

So, only way to create a constructor of abstract or base class and call base constructor from derived class, as like follows.

public DerivedClass() : base() {
    // Do additional work here otherwise you can leave it empty
}

in short, the field initializers run before any constructor in the inheritance chain. So at that time the object is not yet constructed in this sense, so the non-static members cannot be used.

Check out this related many time quoted article

If these are some initial values, one solution would be to refactor the A*B assignment to use the configuration parameter directly.

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