【问题标题】:C# Using a structC# 使用结构
【发布时间】:2012-11-14 06:57:20
【问题描述】:

我正在使用 Mono Develop For Android,在使用结构数组方面需要一些帮助。

这是我的代码:

public struct overlayItem
{
    string stringTestString;
    float floatLongitude;
    float floatLatitude;
}

当使用这个结构时:

overlayItem[1] items;
items[0].stringTestString = "test";
items[0].floatLongitude = 174.813213f;
items[0].floatLatitude = -41.228162f;

items[1].stringTestString = "test1";
items[1].floatLongitude = 170.813213f;
items[1].floatLatitude = -45.228162f;

我在该行收到以下错误:

overlayItem[1] items;

意外的符号“项目”

能否请我帮忙正确地创建一个上述结构的数组,然后用数据填充它。

谢谢

【问题讨论】:

标签: c# arrays struct monodevelop


【解决方案1】:

像这样定义你的结构:

overlayItem[] items = new overlayItem[2];

您还需要将结构中的字段定义为公共字段,以便能够在结构外访问它们

public struct overlayItem
{
    public string stringTestString;
    public float floatLongitude;
    public float floatLatitude;
}

(您可以使用Pascal case 作为您的结构名称)

【讨论】:

  • +1 用于添加 Pascal Case 并指向要公开的属性。
  • @Asif:字段,而不是属性。虽然有时结构应该具有在语义上与字段不同的属性,但如果结构成员的行为类似于公共字段,则它应该是公共字段。
【解决方案2】:

您需要像这样创建结构数组:

overlayItem[] items = new overlayItem[2];

记得用 [2] 声明它,因为它将有 2 个元素,而不是 1 个!索引数组可能从零开始,但定义数组大小不会。

【讨论】:

    【解决方案3】:

    您的示例代码显示您需要两个项目,因此您需要声明长度为 2 的结构数组。这可以通过以下方式完成:

    overlayItem[] items = new overlayItem[2];
    

    【讨论】:

      【解决方案4】:

      为两个元素声明结构数组的正确方法是

      overlayItem[] items = new overlayItem[2];
      

      如果您不知道确切的项目数,您也可以使用列表。

      List<overlayItem> items = new List<overlayItem>();
      
      items.Add( new overlayItem {
                     stringTestString = "test";
                     floatLongitude = 174.813213f;
                     floatLatitude = -41.228162f; 
                 }
      );
      

      【讨论】:

        猜你喜欢
        • 2014-07-25
        • 2016-04-12
        • 2017-11-10
        • 2010-10-26
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多