簡體   English   中英

C# 使用結構

[英]C# Using a struct

我正在使用 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;

意外的符號“項目”

我可以請一些幫助以正確創建上述結構的數組,然后用數據填充它嗎?

謝謝

定義您的結構,如:

overlayItem[] items = new overlayItem[2];

您還需要將結構中的字段定義為公共字段,以便能夠在結構外訪問它們

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

(您可以使用Pascal 大小寫作為您的結構名稱)

為兩個元素聲明結構數組的正確方法是

overlayItem[] items = new overlayItem[2];

如果您不知道項目的確切數量,您也可以使用列表。

List<overlayItem> items = new List<overlayItem>();

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

您需要像這樣創建結構數組:

overlayItem[] items = new overlayItem[2];

請記住用 [2] 聲明它,因為它將有 2 個元素,而不是 1 個! 索引數組可能從零開始,但定義數組大小不是。

您的示例代碼顯示您需要兩個項目,因此您需要聲明長度為 2 的結構數組。這可以通過以下方式完成:

overlayItem[] items = new overlayItem[2];

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM