2014-11-06 33 views
0

我有一个名为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这样的循环。

+1

调查反射和linq的组合http://stackoverflow.com/questions/451453/how-to-get-a-static-property-with-反射 – TGH 2014-11-06 05:45:41

+0

+1这使得很多感......感谢提示@TGH – Elegiac 2014-11-06 05:51:31

+0

如果'CommonImage'类是由您创建的,为什么您不能只创建返回所需的静态方法'ImageCollection'? – Fabio 2014-11-06 05:58:55

回答

0

试试这个: -

var query = typeof(CommonIcons).GetProperties().Where(x => x.Name.Contains("RS")).Select(x => x.Name).ToList(); 
+0

有没有办法我可以将它保存在imageCollection不带循环? – Elegiac 2014-11-06 05:54:43

+0

@Elegiac - 此查询将返回属性名称列表。你想要图像收集? – 2014-11-06 05:57:02

+0

imageCollection是一个控件...对不起,我忘了提及...顺便说一句,上面的列表返回“字符串”,而不是图像,因为你选择“名称”,我想...我们如何选择图像呢? – Elegiac 2014-11-06 06:00:31

0

,如果你尝试这样的..

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; 
+0

这里我假设所有“RS”属性的返回类型都是位图。 否则会引发类型转换异常。 – 2014-11-06 10:06:07

0

我不会进入反射这样的非动态的东西,只是定义了一个额外的属性静态地:

public static ImageCollection RSImages 
{ 
    get 
    { 
     var ic = new ImageCollection(); 
     ic.Add(RSConsDark); 
     ic.Add(RSConsLight); 
     //etc 
     return ic; 
    } 
} 
+0

好主意..FYI ..我认为ImageCollection没有像这样的构造..谈论System.Windows.Forms.ImageList.ImageCollection – 2014-11-06 11:17:58