简体   繁体   中英

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

The error message was :

Error   1   A field initializer cannot reference the non-static field, method, or property 'AmazingPaintball.Form1.thePoint'    

This is the constructor:

namespace AmazingPaintball
{
class Paintball
{
    public Point startPoint;


    public Paintball(Point myPoint)
    {
        startPoint = myPoint;


    }

This is the code that causes the error:

    Point thePoint = new Point(50, 50);
    Paintball gun = new Paintball(thePoint);

You haven't shown enough context, but I suspect you've got something like:

class Game
{
    Point thePoint = new Point(50, 50);
    Paintball gun = new Paintball(thePoint);
}

As the compiler says, a field initializer can't refer to another field or an instance member. The solution is simple though - put the initialization in the constructor:

class Game
{
    Point thePoint;
    Paintball gun;

    public Game()
    {
        thePoint = new Point(50, 50);
        gun = new Paintball(thePoint);
    }
}

That's assuming you really need both fields, mind you. If you only actually need a gun field, you can use:

class Game
{
    Paintball gun = new Paintball(new Point(50, 50));
}

(As an aside, I'd strongly advise against variable names beginning with the . The prefix doesn't add any extra information... it's just noise.)

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