初始图像与构造函数

时间:2015-10-20 21:39:50

标签: c#

我创建了一个课程" Drink"

饮料有两个变量

一个是饮料名称,另一个是饮料的图片

public class Drink
{
    public string name {get; set; }
    public Image pic {get; set; }
}

并初始化。

List<Drink> ex = new List<Drink>
{
   new Drink { name = "juice", pic = "Assets/juice.png" },
   new Drink { name = "water", pic = "Assets/water.png" }
};

但pic的路径错了,如何将图片设置为每个?

更新: error message

2 个答案:

答案 0 :(得分:1)

Drink班级pic属性类型Image中,但您要分配string,它应该是:

List<Drink> ex = new List<Drink>
{
   new Drink { name = "juice", pic = Image.FromFile("Assets/juice.png") },
   new Drink { name = "water", pic = Image.FromFile("Assets/water.png") }
};

msdn上查看Image.FromFile方法。

答案 1 :(得分:0)

您的要求并不完全清楚,但您需要在初始化程序中传递Image,而不是string。在下面的示例中,Bitmap派生自Image

List<Drink> ex = new List<Drink>
{
   new Drink { name = "juice", pic = new Bitmap("Assets/juice.png") },
   new Drink { name = "water", pic = new Bitmap("Assets/water.png") }
};