我有一个人类,如下图所示,图像作为属性。我试图弄清楚如何在我的程序类中创建person类的实例,并将对象的图像设置为文件路径,例如C:\用户\文档\ picture.jpg。我该怎么做?
public class Person
{
public string firstName { get; set; }
public string lastName { get; set; }
public Image myImage { get; set; }
public Person()
{
}
public Person(string firstName, string lastName, Image image)
{
this.fName = firstName;
this.lName = lastName;
this.myImage = image;
}
}
答案 0 :(得分:1)
使用无参数构造函数,如下所示:
Person person = new Person();
Image newImage = Image.FromFile(@"C:\Users\Documents\picture.jpg");
person.myImage = newImage;
虽然使用其他构造函数应该是首选方法
答案 1 :(得分:1)
一种选择是:
public Person(string firstName, string lastName, string imagePath)
{
...
this.myImage = Image.FromFile(imagePath);
}
答案 2 :(得分:1)
试试这样:
public class Person
{
public string firstName { get; set; }
public string lastName { get; set; }
public Image myImage { get; set; }
public Person()
{
}
public Person(string firstName, string lastName, string imagePath)
{
this.fName = firstName;
this.lName = lastName;
this.myImage = Image.FromFile(imagePath);
}
}
并实例化如下:
Person p = new Person("John","Doe",@"C:\Users\Documents\picture.jpg");
答案 3 :(得分:1)
其他人已经建议Image.FromFile
。您应该知道这将锁定文件,这可能会导致以后出现问题。更多阅读:
Why does Image.FromFile keep a file handle open sometimes?
请考虑使用Image.FromStream
方法。这是一个采用路径并返回图像的示例方法:
private static Image GetImage(string path)
{
Image image;
using (var fs = new FileStream(path, FileMode.Open, FileAccess.Read))
{
image = Image.FromStream(fs);
}
return image;
}
此方法的值是您可以在打开和关闭文件句柄时进行控制。