【问题标题】:Receiving the following error while attempting to compare struct member values尝试比较结构成员值时收到以下错误
【发布时间】:2021-12-14 14:20:02
【问题描述】:

我刚刚开始探索 c# 的世界。 我一直在使用用户定义的类型 如下:

struct Obstacle
    {
        public static int x1 { get; set; }
        public static int y1 { get; set; }
        public static int x2 { get; set; }
        public static int y2 { get; set; }

        public Obstacle(int X1, int Y1, int X2, int Y2)
        {
            x1 = X1;
            y1 = Y1;
            x2 = X2;
            y2 = Y2;
        }
    }

我在另一个文件包含的 classA 中构造了这些类型的列表。

List<Obstacle> o = new();

按照向列表添加元素的过程 我尝试比较特定列表元素的两个坐标(也在 classA 内):

for (int i = 0; i < obstacle_count; i++)
{
   if (o.ElementAt(i).x1 != obstacles.ElementAt(i).x2)
   {
        //do something
   }
   else
   {
        //do something else
   }
}

但是我收到类似这样的错误:“无法使用实例引用访问成员 'Obstacle.x1';改为使用类型名称对其进行限定”。

结构定义与上面介绍的其他代码 sn-ps 共享命名空间。

我应该如何解决这个问题?提前谢谢。 :)

【问题讨论】:

  • 成员 x1, x2, y1,y2 是静态的,这意味着 Obstacle 类型的所有对象共享这些字段。在您的情况下,它们真的应该是静态的吗?

标签: c# list struct


【解决方案1】:

我相信这是因为 x1, x2 , ... 是静态的。你不能用函数影响静态值:)

【讨论】:

    猜你喜欢
    • 2021-10-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-17
    • 2014-10-12
    相关资源
    最近更新 更多