C#ArrayList中从获取对象的属性 [英] c# Get object property from ArrayList
问题描述
想不通这一个
我的班级一个ArrayList
//保存图像
公共类productImage
{
公众诠释imageID;
公共字符串IMAGEURL;
公众的DateTime dateAdded;
公共字符串slideTitle;
公共字符串slideDescrip;
} 公共ArrayList的productImages =新的ArrayList();productImage newImage =新productImage();
newImage.imageID = 123;
productImages.Add(newImage);
现在我怎么访问属性?
INT东西= productImages [0] .imageID
不行!
错误1对象不包含
定义slideTitle无
扩展方法slideTitle
接受类型的第一个参数
对象可以找到(你
缺少using指令或程序
集引用?)
块引用>解决方案在
的ArrayList
被键入到对象的值
。你需要转换为productImage
来访问属性。INT东西=((productImage)productImages [0])imageId。
有一个更好的解决方案,虽然是使用强类型集合像
列表< T>
。您可以指定元素类型是productImage
并完全避免铸件。公开名单< productImage> productImages =新的List< productImage>();
productImage newImage =新productImage();
newImage.imageID = 123;
productImages.Add(newImage);
INT东西= productImages [0] .imageID; //作品Can't figure this one out
I have an ArrayList of classes:
// 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);
Now how do I access the property?
int something = productImages[0].imageID
Doesn't work!
Error 1 'object' does not contain a definition for 'slideTitle' and no extension method 'slideTitle' accepting a first argument of type 'object' could be found (are you missing a using directive or an assembly reference?)
解决方案The values in an
ArrayList
are typed toObject
. You need to cast toproductImage
to access the property.int something = ((productImage)productImages[0]).imageId;
A much better solution though is to used a strongly typed collection like
List<T>
. You can specify the element type isproductImage
and avoid the casting altogether.public List<productImage> productImages = new List<productImage>(); productImage newImage = new productImage(); newImage.imageID = 123; productImages.Add(newImage); int something = productImages[0].imageID; // Works
这篇关于C#ArrayList中从获取对象的属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!