[英]c# Get object property from 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'接受類型'object'的第一個參數可以找到(你是否缺少using指令或程序集引用?)
ArrayList
中的值鍵入Object
。 您需要productImage
轉換為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
嘗試:
int something = ((productImage)productImages[0]).imageID;
需要從類型對象中轉換。
只是為了用現代習語來獲得這個代碼:
public ArrayList productImages = new ArrayList();
productImage newImage = new productImage();
newImage.imageID = 123;
productImages.Add(newImage);
可以重寫為:
var productImages = new List<ProductImage> { new ProductImage { ImageID = 123 } };
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.