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

本小妞迷上赌 提交于 2019-12-25 18:33:32

问题


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

回答1:


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



来源:https://stackoverflow.com/questions/24915423/getting-error-a-field-initializer-cannot-reference-the-non-static-field-method

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!