【问题标题】:For loop to add image to imagelistFor循环将图像添加到图像列表
【发布时间】:2014-04-09 13:30:51
【问题描述】:

我正在清理我的代码,试图在某些方面做空

现在我偶然发现:

  ImageList.Add(test.Properties.Resources.test1);
  ImageList.Add(test.Properties.Resources.test2);
  ImageList.Add(test.Properties.Resources.test3);
  ImageList.Add(test.Properties.Resources.test4);
  ImageList.Add(test.Properties.Resources.test5);

(其中有 15 个) 想知道这是否可以用 for 循环缩短

类似:

for(int i=1; i<=15; i++)
        ImageList.Add(test.Properties.Resources.test +i);

现在这当然行不通,但我不知道该怎么做(如果可能的话)

【问题讨论】:

  • Resources 是否有可枚举 个您可以使用的这些值?您正在尝试的方法可以通过反射来完成,但这对于这样的事情通常是矫枉过正的。理想情况下,Resources 应该公开这些图像的集合,然后您可以在该集合上添加一个循环(或者甚至通过使用.Select() 转换集合直接分配给ImageList)。
  • 发生了好几次,我想知道这样的事情是否存在。
  • 如果那些在你的Resources 对象中的任何类型的集合中,那会很容易,但是对于当前的设计,它不可能以一种干净的方式。不过,您可能希望更新您的设计,如果您希望扩大收藏的规模,这将使其更具未来性。
  • ResourceManager 会工作吗?

标签: c# for-loop


【解决方案1】:

您可以通过此代码迭代资源

using System.Collections;
using System.Globalization;
using System.Resources;

...

ResourceSet resourceSet = MyResourceClass.ResourceManager.GetResourceSet(CultureInfo.CurrentUICulture, true, true);
foreach (DictionaryEntry entry in resourceSet)
{
    string resourceKey = entry.Key;
    object resource = entry.Value;
}

【讨论】:

    【解决方案2】:

    您可以使用反射来获取值:

    public class Something
    {
        public int Test1 { get; set; }
        public int Test2 { get; set; }
        public int Test3 { get; set; }
        public int Test4 { get; set; }
    }
    
    
    var thing = new Something();
    
    var imageProperties = typeof(Something)
        .GetProperties()
        .Where(p => p.Name.StartsWith("Test"));
    
    var imagesToAdd = imageProperties
        .Select(property => property.GetValue(thing))
        .ToList();
    

    【讨论】:

      【解决方案3】:

      您可以在Resources 对象的类中定义IEnumerable&lt;Image&gt; 类型的属性

      public IEnumerable<Image> Images
      {
          get
          {
              yield return test1;
              yield return test2;
              yield return test3;
              yield return test4;
              yield return test5;
              ...
          }
      }
      

      然后用它来填充ImageList

      foreach(var image in test.Properties.Resources.Images)
      {
           ImageList.Add(image); 
      }
      

      【讨论】:

        【解决方案4】:

        我刚刚发现有一个用于评估 C# 表达式的库,称为 Flee。显然,您可以使用它来评估 C# 代码,以便您可以循环变量名称,就像 JavaScript 一样,但对它的需求很可能意味着设计缺陷。

        http://flee.codeplex.com/

        【讨论】:

          猜你喜欢
          • 2023-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2020-01-06
          • 1970-01-01
          相关资源
          最近更新 更多