这个问题在这里已经有了答案:
A field initializer cannot reference the nonstatic field, method, or property
(4 个回答)
7年前关闭。
当我编译下面的代码时,编译器给出错误:字段初始值设定项无法引用此代码中的非静态字段、方法或属性(有星号)
KingPiece kingPiece = new KingPiece(***siyahsah1***,ChessColor.White);
谁能帮我?
class PiecePosition
{
public enum ChessColor
{
White,
Black,
}
public class ChessPiece
{
private Image DisplayedImage;
private ChessColor DisplayedColor;
private Point CurrentSquare;
public Point[] ValidMoves;
public ChessPiece(Image image, ChessColor color)
{
DisplayedImage = image;
DisplayedColor = color;
}
}
public class KingPiece : ChessPiece
{
public KingPiece(Image image, ChessColor color)
: base(image, color)
{
ValidMoves[0] = new Point(0, -1); // Up 1
ValidMoves[1] = new Point(1, -1); // Up 1, Right 1
ValidMoves[2] = new Point(1, 0); // Right 1
ValidMoves[7] = new Point(-1, -1); // Left 1, Up 1
}
System.Drawing.Bitmap siyahsah1 = chess6.Properties.Resources.siyahsah1;
KingPiece kingPiece = new KingPiece(siyahsah1,ChessColor.White);
}
}
最佳答案
您应该将该行移动到构造函数中:
kingPiece = new KingPiece(siyahsah1,ChessColor.White);
问题是您还没有类实例,编译器不喜欢这样。如果您只是将该行移动到构造函数中,它将起作用。
您仍然必须将该属性定义为私有(private)字段。你可以这样做:
private KingPiece kingPiece;
在第一行的当前位置执行此操作。最终结果将与您现在发出的完全一样,只是它会编译。
关于c# - 编译错误 :A field initializer cannot reference the non-static field, 方法或属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4114006/