c# - 编译错误 :A field initializer cannot reference the non-static field, 方法或属性

标签 c# compiler-errors chess

这个问题在这里已经有了答案:





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/

相关文章:

c# - DTO 与序列化持久化实体

c# - 作为 XAML 元素的附加属性

java - 如何在 Java 13 和 Spring 的 Maven 中修复不受支持的类文件主要版本 57

c++ - 国际象棋游戏-程序崩溃

c# - 具有多个位置的动画绘图 LineRenderer

c# - 如何知道 File.Copy 成功了?

Haskell Map函数实现问题

c++ - C++ 中的嵌套类错误

c# - 描述国际象棋规则的推荐数据格式

java - 网格颜色变化