C# 我不明白为什么我得到CS0120

C# 我不明白为什么我得到CS0120,c#,C#,我有一个错误,在我的书中寻找答案,并观看了关于这个特定主题的教程。较大的间隙表示我添加的另一类,称为点 class Program { private static Point another; static void Main(string[] args) { Point origin = new Point(1366, 768); Point bottomRight = anoth

我有一个错误,在我的书中寻找答案,并观看了关于这个特定主题的教程。较大的间隙表示我添加的另一类,称为

    class Program
    {
        private static Point another;
        static void Main(string[] args)
        {
            Point origin = new Point(1366, 768);
            Point bottomRight = another;
            double distance = origin.DistanceTo(bottomRight);
            Console.WriteLine("Distance is: {0}", distance);
            Console.WriteLine("Number of Point objects: {0}", Point.ObjectCount());
        }
    }
class Point { 
    private int x, y;
        private int objectCount = 0;
        public Point()
        {
            this.x = -1;
            this.y = -1;
            objectCount++;
        }
        public Point(int x, int y)
        {
            this.x = x;
            this.y = y;
            objectCount++;
        }
        public double DistanceTo(Point other)
        {
            int xDiff = this.x - other.x;
            int yDiff = this.y - other.y;
            double distance = Math.Sqrt((xDiff * xDiff) + (yDiff * yDiff));
            return distance;
        }
        public static int ObjectCount()
        {
            **return objectCount;** 
        }
    }
您的
ObjectCount()
方法是
静态方法,而您的属性不是

public static int ObjectCount()
当您从代码中未分配的属性读取时。因此,从方法签名中删除static关键字

public int ObjectCount()
{
    return objectCount;
}
1) 请在单独的区块中发布完整的代码,也请告诉人们错误的确切位置

2) 我猜错误CS0120来自以下行:Console.WriteLine(“点对象的数量:{0}”,Point.ObjectCount())

再一次,我猜您想要计算创建的所有点对象。您的错误是将objectCount作为实例成员

您可以看到,Point类的每个实例都有自己的objectCount,并且在构造函数完成后它始终为1。出于同样的原因,您不能调用Point.ObjectCount()并从中返回ObjectCount,因为ObjectCount不是静态成员,而是绑定到实例


要修复代码,请将objectCount设置为静态。这样,Point的所有实例将只有一个objectCount。

欢迎来到我们的社区。请注意,为了得到他人的帮助,您必须发布一个好问题。从代码中删除不必要的部分并简化它,当然不要使用空格。如果你想让别人把时间花在你的问题上,你必须是第一个关心和花费时间的人