简体   繁体   English

在C#中添加到ImageList时,Image.Tag为null

[英]Image.Tag is null when added to ImageList in C#

I have the following code which reads a image from a Url and adds the image to a ImageList. 我有以下代码,该代码从Url读取图像并将图像添加到ImageList。

WebClient oWebClient = new WebClient();
Uri oUri = new Uri("http://www.mysite.com/images/image1.jpg");

try
{
    Image oImage = Image.FromStream(oWebClient.OpenRead(oUri));
    oImage.Tag = "hello World";
    imageList1.Images.Add("test", oImage);
}
catch(Exception ex)
{
    listBox1.Items.Add("Error getting photo: " + ex.Message);
}

Everything works fine, except for some reason the Image tag is empty when I inspect it in the imageList1 object ? 一切正常,除了出于某种原因,当我在imageList1对象中检查Image标记时,该标记为空? Why is this happening ? 为什么会这样呢?

I would steer away from using the Tag property on objects, as it can be unreliable (as you see) as well as not being very extensible. 我会避免在对象上使用Tag属性,因为它可能不可靠(如您所见),并且可能无法很好地扩展。

In your case ImageList.Add(key, image) uses the key parameter is so you can retrieve that Image later using ImageList[key] indexer property. 在您的情况下, ImageList.Add(key, image)使用key参数,因此以后可以使用ImageList[key]索引器属性检索该Image

If you are trying to store more data into the Tag property, I would recommend you instead create your own data model class and use that instead. 如果您试图将更多数据存储到Tag属性中,建议您创建自己的数据模型类并使用它。

It is much easier to keep a List<T> or Dictionary<Key, Value> of your type for retrieval instead of playing with Tag casting/lookup. 保留要检索的类型的List<T>Dictionary<Key, Value>而不是使用Tag强制转换/查找要容易得多。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM