2014-11-06 83 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