2010-09-08 48 views
2

對象屬性想不通這一個C#獲取從ArrayList中

我擁有類的ArrayList:

 // Holds an image 
     public class productImage 
     { 
      public int imageID; 
      public string imageURL; 
      public DateTime dateAdded; 
      public string slideTitle; 
      public string slideDescrip; 
     } 

    public ArrayList productImages = new ArrayList(); 

productImage newImage = new productImage(); 
newImage.imageID = 123; 
productImages.Add(newImage); 

現在我該怎樣訪問屬性?

int something = productImages[0].imageID 

不行!

錯誤1「對象」不包含 定義爲「slideTitle」和無 擴展方法「slideTitle」 接受型 「對象」的第一個參數可以發現(你 缺少using指令或程序 集引用?)

+1

不要使用.NET 2.0和更高版本的ArrayList。 – 2010-09-08 16:08:20

回答

11

ArrayList的值輸入到Object。您需要投入productImage才能進入酒店。

int something = ((productImage)productImages[0]).imageId; 

一個更好的解決方案,雖然是使用強類型集合像List<T>。您可以指定元素類型爲productImage並避免完全投射。

public List<productImage> productImages = new List<productImage>(); 
productImage newImage = new productImage(); 
newImage.imageID = 123; 
productImages.Add(newImage); 
int something = productImages[0].imageID; // Works 
1

嘗試:

int something = ((productImage)productImages[0]).imageID; 

需要從object類型鑄造。

0

只是爲了得到這個代碼了現代成語:

public ArrayList productImages = new ArrayList(); 

productImage newImage = new productImage(); 
newImage.imageID = 123; 
productImages.Add(newImage); 

可以重新寫爲:

var productImages = new List<ProductImage> { new ProductImage { ImageID = 123 } }; 
+0

謝謝,但爲簡單起見,我減少了問題中的代碼,實際代碼處於循環獲取數據庫記錄 – 2010-09-08 15:44:00

+0

mmmmmmmmk。我知道了 :) – 2010-09-08 15:47:18