Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
286 views
in Technique[技术] by (71.8m points)

c# - 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);
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...