簡體   English   中英

你能在結構中聲明 object 類型嗎

[英]Can you declare object types in struct

我對來自 c++ 背景的 c# 真的很陌生 我正在努力使用 c++ 中的數據結構,例如

struct product {
  int weight;
  double price;
} apple[10];

現在問題 c# 不會讓我這樣做,因為在 c# 中,當我聲明像蘋果這樣的 object 類型時,我現在無法訪問重量或價格。 有沒有辦法聲明 object 類型數組? 像上面我知道我能做到

product apple = new product();

但我收到一個錯誤,無法將帶有 [] 的索引應用於 Program.product 類型的表達式。 有沒有辦法用數據結構應用索引我想做的就是這樣。

struct product {
  int x;
  double w;
} array[10];

for (int i = 0 ; i < 5 ; i++ ){

array[i].x = array[i - 1].x

}

我感謝您的幫助。

C#中的成員變量默認是private的,所以需要在type和name前加上public。

同樣要創建一個數組,您需要使用 new 關鍵字。

public struct product 
{
  public int x;
  public double w;
}

var products = new product[10];

for (int i = 1 ; i < 5 ; i++ )
{
  products [i].x = products [i - 1].x; // beware 0-1 = -1
}

結構的實例是值類型,而不是引用對象的類的實例(隱藏的托管指針忘記管理它們)。

這可能會幫助您:

結構(C# 參考)

暫無
暫無

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

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