C#ArrayList中从获取对象的属性 [英] c# Get object property from ArrayList

查看:1007
本文介绍了C#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 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

这篇关于C#ArrayList中从获取对象的属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆