我可以将图像与类关联并加载此图像而无需创建类的实例吗?

时间:2011-03-10 20:29:07

标签: image attributes c#-2.0

长时间潜伏,第一次在这里张贴海报。

我的问题是:

使用C#2.0,是否有办法将am image与类/类型相关联,这样我就不必创建类的实例来获取该类的图像对象?

我要做的是扫描我的应用程序中的所有.dll并构建一​​个类列表和相应的属性。我有这个很好的工作,现在我想以某种方式将图像与每个类相关联,这样我就可以显示一个类列表,并为每个类创建一个独特的图像。

我试过搜索SO和互联网寻找答案,但找不到任何明确的答案。任何帮助将不胜感激。

谢谢,

凯尔

2 个答案:

答案 0 :(得分:0)

您可以创建一个ImageAttribute。

[AttributeUsage(AttributeTargets.Class, AllowMultiple = false)]
class ImageAttribute : Attribute
{
    private string ImagePath { get; set; } 

    public ImageAttribute(string imagePath)
    {
        ImagePath = imagePath;
    }

    public Bitmap Image
    {
        get { return new Bitmap(ImagePath); }
    }
}

或数据库ID,只是识别图像的一种方式。

答案 1 :(得分:0)

想出如何在这里和那里使用想法。

  1. 将图像标记为EmbeddedResource。

  2. 创建用于指定图像名称的属性。

  3. 读取图像名称属性后,使用以下命令查找声明该类的程序集内的图像资源:

    string[] all = info.Type.Assembly.GetManifestResourceNames();
    
    foreach (string resourceStr in all)
    {
      if (!String.IsNullOrEmpty(resourceStr) && resourceStr.EndsWith(String.Format(".{0}", iconName), true, CultureInfo.CurrentCulture))
      {
        Stream file = info.Type.Assembly.GetManifestResourceStream(resourceStr);
    
        if (file != null)
        {
          info.Icon = Image.FromStream(file);
        }
      }
    }