c# Get object property from ArrayList

a 夏天 提交于 2019-12-23 22:10:05

问题


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?)


回答1:


The values in an ArrayList are typed to Object. You need to cast to productImage 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 is productImage 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



回答2:


try:

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

Needs to be casted from the type object.




回答3:


Just to get this code up with modern idioms:

public ArrayList productImages = new ArrayList();

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

can be re-written as:

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


来源:https://stackoverflow.com/questions/3669392/c-sharp-get-object-property-from-arraylist

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!