将System.Drawing.SystemIcons转换为ImageList时遇类型错误求助
解决SystemIcons转ImageList的报错问题
错误原因
报错'SystemIcons' is a type, which is not valid in the given context是因为PropertyInfo.GetValue()获取静态属性时,不需要传入实例对象,你传入的SystemIcons是类型本身,不符合参数要求。SystemIcons的所有图标属性都是静态的,这里应该传null。
修正后的代码
ImageList iconlist = new ImageList(); // 按需设置图标大小,适配ListView显示 iconlist.ImageSize = new Size(32, 32); // 只过滤公开的静态图标属性 PropertyInfo[] properties = typeof(SystemIcons).GetProperties(BindingFlags.Public | BindingFlags.Static); foreach (PropertyInfo property in properties) { Debug.WriteLine(property.Name); Icon icon = property.GetValue(null) as Icon; if (icon != null) { iconlist.Images.Add(property.Name, icon.ToBitmap()); } }
额外优化说明
- 增加
BindingFlags过滤,精准获取需要的静态图标属性,避免冗余数据。 - 加入空值判断,防止图标转换失败时抛出异常。
- 可通过
ImageSize调整图标尺寸,匹配ListView的显示需求。
内容的提问来源于stack exchange,提问作者RémiG
相关产品推荐
相关产品推荐

