错误消息是:
Error 1 A field initializer cannot reference the non-static field, method, or property 'AmazingPaintball.Form1.thePoint'
Run Code Online (Sandbox Code Playgroud)
这是构造函数:
namespace AmazingPaintball
{
class Paintball
{
public Point startPoint;
public Paintball(Point myPoint)
{
startPoint = myPoint;
}
Run Code Online (Sandbox Code Playgroud)
这是导致错误的代码:
Point thePoint = new Point(50, 50);
Paintball gun = new Paintball(thePoint);
Run Code Online (Sandbox Code Playgroud)
你没有展示足够的背景,但我怀疑你有类似的东西:
class Game
{
Point thePoint = new Point(50, 50);
Paintball gun = new Paintball(thePoint);
}
Run Code Online (Sandbox Code Playgroud)
正如编译器所说,字段初始值设定项不能引用另一个字段或实例成员.解决方案很简单 - 将初始化放在构造函数中:
class Game
{
Point thePoint;
Paintball gun;
public Game()
{
thePoint = new Point(50, 50);
gun = new Paintball(thePoint);
}
}
Run Code Online (Sandbox Code Playgroud)
假设你确实需要两个领域,请注意.如果您只需要一个gun字段,您可以使用:
class Game
{
Paintball gun = new Paintball(new Point(50, 50));
}
Run Code Online (Sandbox Code Playgroud)
(顺便说一句,我强烈建议不要以变量名开头the.前缀不会添加任何额外的信息......它只是噪音.)