返回静态类的所有选定属性值
我有一个名为CommonImage的静态类,它具有静态位图的属性,可以随时获取。 继承人我实际类:返回静态类的所有选定属性值
public static class CommonImage
{
public static Bitmap AccountConnected { get; }
public static Bitmap AccountDisconnected { get; }
public static Bitmap ArrowDownIcon { get; }
public static Bitmap ArrowUpIcon { get; }
public static Bitmap AutoScrollIcon { get; }
public static Bitmap RSConsDark { get; }
public static Bitmap RSConsLight { get; }
public static Bitmap RSDelDark { get; }
public static Bitmap RSDelLight { get; }
}
什么我想要做的:
我想获得所有属性/形象的startsWith “RS”并存储在一个ImageCollection
所有图像。 并且如果可能的话,没有像foreach和forloop这样的循环。
试试这个: -
var query = typeof(CommonIcons).GetProperties().Where(x => x.Name.Contains("RS")).Select(x => x.Name).ToList();
,如果你尝试这样的..
var query = typeof(CommonImage).GetProperties().Where(x => x.Name.Contains("RS")).Select(x => x.Name).ToList();
var ImageList = new ImageList();
query.ForEach(propName => ImageList.Images.Add((Bitmap)typeof(CommonImage).GetProperty(propName).GetValue(typeof(CommonImage), null)));
System.Windows.Forms.ImageList.ImageCollection col = ImageList.Images;
这里我假设所有“RS”属性的返回类型都是位图。 否则会引发类型转换异常。 – 2014-11-06 10:06:07
我不会进入反射这样的非动态的东西,只是定义了一个额外的属性静态地:
public static ImageCollection RSImages
{
get
{
var ic = new ImageCollection();
ic.Add(RSConsDark);
ic.Add(RSConsLight);
//etc
return ic;
}
}
好主意..FYI ..我认为ImageCollection没有像这样的构造..谈论System.Windows.Forms.ImageList.ImageCollection – 2014-11-06 11:17:58
调查反射和linq的组合http://stackoverflow.com/questions/451453/how-to-get-a-static-property-with-反射 – TGH 2014-11-06 05:45:41
+1这使得很多感......感谢提示@TGH – Elegiac 2014-11-06 05:51:31
如果'CommonImage'类是由您创建的,为什么您不能只创建返回所需的静态方法'ImageCollection'? – Fabio 2014-11-06 05:58:55