【问题标题】:How to access array created from a struct?如何访问从结构创建的数组?
【发布时间】:2020-05-22 00:26:09
【问题描述】:

我创建了一个名为 citys 的结构体,并在结构体之外创建了一个带有参数的城市类型数组。我正在尝试访问该数组,但它不适合我。非常感谢任何帮助!

public struct cities
{
    public int x;
    public int y;
    public int windSpeed;
    public string nameCity;

    public cities(int _x, int _y, int _windSpeed, string _nameCity)
    {
        x = _x;
        y = _y;
        windSpeed = _windSpeed;
        nameCity = _nameCity;
    }


}


cities[] citywinds =
{
    new cities(171,197,1,"Goodland"),
    new cities(422,195,1,"Hill City"),
    new cities(796,239,1,"Manhattan"),
    new cities(908,243,1,"Topeka"),
    new cities(941,490,1,"Chanute"),
    new cities(706,475,1,"Wichita"),
    new cities(389,450,1,"Dodge City"),
    new cities(281,418,1,"Garden City"),
    new cities(997,110,1,"Cameron"),
    new cities(1044,361,1,"El Dorado Springs"),
    new cities(1024,577,1,"Monett"),
    new cities(749,575,1,"Ponca City"),
    new cities(720,95,1,"Beatric"),
    new cities(452,92,1,"Kearney"),
    new cities(457,573,1,"West Woodward"),
    new cities(128,568,1,"Elkhart"),
    new cities(120,88,1,"Akron")
};


citywinds[1]._windspeed; //not working

【问题讨论】:

  • 所以这是一个粘贴实际代码的练习。和实际的错误消息,即使有最好的假设,仍然很难弄清楚实际问题是什么
  • 缩进和命名约定有助于理解代码。
  • C 不同,CSharp 中的所有项目都需要在类中声明。您的 citywinds 变量只是在空中分发。

标签: c# arrays struct


【解决方案1】:

你的前缀是下划线

citywinds[1]._windspeed

房产在哪里

public int windSpeed;

试试这个

var speed = citywinds[1].windSpeed;

如果它是班级成员,您还需要将cities[] citywinds 标记为static。这可能是你的另一个问题

static cities[] citywinds

Demo here

【讨论】:

  • @Araasai 以上应该可以工作,除非这不是你的代码
  • 我把这个“int x = citywinds[1].windspeed;”我收到此错误消息“字段初始化程序无法引用非静态字段”
  • 与“var speed = citywinds[1].windspeed;”相同的错误
  • @John 谢谢你,有点困惑
  • 如果您在 main 中定义 citywinds,则不必担心添加静态修饰符,但如果您将其创建为全局变量(在 Main 之外),则需要将其创建为静态,因为您正在从声明为静态的Main 中访问它。
猜你喜欢
  • 2019-12-03
  • 2018-06-08
  • 2017-01-28
  • 2014-01-21
  • 2022-01-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多