日期:2014-05-17  浏览次数:20918 次

imagelist.images[0].tag无法赋值
            imageList1.Images[0].Tag = "000";
            MessageBox.Show(imageList1.Images[0].Tag.ToString());//出错!!!

            注:已经为imagelist1添加了几张图片。
错误信息为:未将对象引用设置到对象的实例

------解决方案--------------------
在ImageList中获取某索引处的图片是创建新图,因此设置Tag无效,每次访问该属性得到的都是不同的Image对象,为什么每次都要创建新图而不是缓存图片就不知道了。
public sealed class ImageList : Component
{
    private ImageList owner;

    public Image this[int index]
    {
        get
        {
            if ((index < 0) 
------解决方案--------------------
 (index >= this.Count))
            {
                throw new ArgumentOutOfRangeException("index", SR.GetString("InvalidArgument", new object[] { "index", index.ToString(CultureInfo.CurrentCulture) }));
            }
            return this.owner.GetBitmap(index);
        }
        set ......
    }
......
}

下面是GetBitmap方法的具体代码:
private Bitmap GetBitmap(int index)
{
    if ((index < 0) 
------解决方案--------------------
 (index >= this.Images.Count))
    {
        throw new ArgumentOutOfRangeException("index", SR.GetString("InvalidArgument", new object[] { "index", index.ToString(CultureInfo.CurrentCulture) }));
    }
    Bitmap image = null;
    if (this.ColorDepth == ColorDepth.Depth32Bit)
    {
        NativeMethods.IMAGEINFO pImageInfo = new NativeMethods.IMAGEINFO();
        if (SafeNativeMethods.ImageList_GetImageInfo(new HandleRef(this, this.Handle), index, pImageInfo))
        {
            Bitmap bitmap2 = null;
            BitmapData bmpData = null;
            BitmapData targetData = null;
            IntSecurity.ObjectFromWin32Handle.Assert();
            try
            {
          &nbs