【问题标题】:load an image from resources in Visual C#, using a string?使用字符串从 Visual C# 中的资源加载图像?
【发布时间】:2016-06-29 08:19:50
【问题描述】:

如果我有一些资源,例如 card1.png、card2.png 等, 我想让他们将它们加载到 picBox 中,但只加载正确的图像 例如,像

int cardNum = rn.Next(0,cardMax);
picCard.Image = Properties.Resources."card"+cardNum+".png";

显然这不起作用,但我将如何做我想做的事情(在将资源名称构建成字符串后加载正确的资源)

【问题讨论】:

  • @AndyKorneyev 这是关于通过匹配内容来查找资源的密钥,而不是按名称加载。
  • 打开 Resources.Designer.resx,您会看到它们是如何通过字符串名称查找的。​​span>
  • 请注意,在向资源添加内容时,扩展名通常会被剥离。虽然在技术上是允许的,但点字符在资源名称中被视为“坏字符”。

标签: c# visual-studio resources


【解决方案1】:

直接使用ResourceManager代替Resources类中生成的属性:

string resName = $"card{cardNum}.png"; // Check the correct name in the .resx file. By using the wizards the extension is omitted, for example.
picCard.Image = (Image)Properties.Resources.ResourceManager.GetObject(resName);

【讨论】:

    【解决方案2】:

    尝试使用:

    var rm = new System.Resources.ResourceManager(((System.Reflection.Assembly)System.Reflection.Assembly.GetExecutingAssembly()).GetName().Name + ".Properties.Resources", ((System.Reflection.Assembly)System.Reflection.Assembly.GetExecutingAssembly()));
    Image img = (Bitmap)rm.GetObject("resourcesimagename.jpg");
    

    【讨论】:

      猜你喜欢
      • 2011-08-29
      • 2012-11-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-07-08
      • 1970-01-01
      • 2010-10-21
      • 2011-01-19
      相关资源
      最近更新 更多