C# Winforms:使用Activator.CreateInstance从资源创建System.Drawing.Image
如果可能的话,我如何使用C# Winforms:使用Activator.CreateInstance从资源创建System.Drawing.Image,c#,winforms,createinstance,C#,Winforms,Createinstance,如果可能的话,我如何使用 Activator.CreateInstance("MyExeName", "Resources.Image1") 要创建与按钮关联的背景图像Image1是在名为“Image1”的资源中定义的图像 我在stackoverflow中没有看到类似的东西。我错过了什么 感谢您的关注,我们非常感谢您的帮助。如果您可以获得所需资源的名称,请使用以下方法: using System.Resources; public static Image GetImage(String
Activator.CreateInstance("MyExeName", "Resources.Image1")
要创建与按钮关联的背景图像Image1
是在名为“Image1”
的资源中定义的图像
我在stackoverflow中没有看到类似的东西。我错过了什么
感谢您的关注,我们非常感谢您的帮助。如果您可以获得所需资源的名称,请使用以下方法:
using System.Resources;
public static Image GetImage(String ImageName)
{
Image retImage = null;
Object o = Properties.Resources.ResourceManager.GetObject(ImageName);
if (o != null && (o is Image))
{
Image img = (Image)((Image)o).Clone(); //necessary to prevent premature disposal
retImage = img;
}
return retImage;
}
这是MSDN,关于它的使用有很多问题。你到底想做什么?这里的目标是什么?听起来您想从应用程序资源中提取图像并将其分配给按钮?那么为什么要使用反射呢?为什么不获取资源并提取它,然后最终将其截取为图像,并将其分配给按钮图像/背景?我正在寻找一种基于按钮名称派生的名称获取资源的方法。我希望避免通过参数列表传入每个单独的资源名称,或者更糟糕的是,避免有一长串重复的资源分配。换句话说,我想循环浏览一个按钮列表,从列表中的按钮名称派生分配资源。对不起,如果这没有意义。如果需要用代码澄清,我可以编辑原始帖子。@Buck反射不是必需的。图像存储为字节流,因此您可以将字节读出到新的
Image
实例中。它只需要一个字符串资源名,您可以根据需要动态构建它。
using System.Resources;
public static Image GetImage(String ImageName)
{
Image retImage = null;
Object o = Properties.Resources.ResourceManager.GetObject(ImageName);
if (o != null && (o is Image))
{
Image img = (Image)((Image)o).Clone(); //necessary to prevent premature disposal
retImage = img;
}
return retImage;
}