我想编写一个函数,它将作为输入字符串 fileName 并返回 ImageDrawing 对象。
我不想在此函数中从磁盘加载位图。相反,我想要进行某种惰性评估。
为了找出尺寸,我使用了 Bitmap 类。
目前我有这个代码:
public static ImageDrawing LoadImage(string fileName)
{
System.Drawing.Bitmap b = new System.Drawing.Bitmap(fileName);
System.Drawing.Size s = b.Size ;
System.Windows.Media.ImageDrawing im = new System.Windows.Media.ImageDrawing();
im.Rect = new System.Windows.Rect(0, 0, s.Width, s.Height);
im.ImageSource = new System.Windows.Media.Imaging.BitmapImage(new Uri(fileName, UriKind.Absolute));
return im;
}
- 对 System.Drawing.Bitmap 构造函数的调用是否是惰性调用?
- 对 .Size 的调用是否是懒惰的?
- BitmapImage 构造函数是否惰性?
- 有没有其他方法可以让我实现完全懒惰?
编辑:
有许多可能对社区有帮助的好答案 - 使用 Lazy 类并通过 Task 打开它。
尽管如此,我想把这个 ImageDrawing 放在 DrawingGroup 中,然后序列化,所以 Lazy 以及 Task 是对我来说不是一个选择。
最佳答案
Bitmap
的构造函数类并不懒惰,但您可以使用 Lazy<T>
正是为了这个目的而创建的类:
public static Lazy<ImageDrawing> LoadImage(string fileName)
{
return new Lazy<ImageDrawing>(() => {
System.Drawing.Bitmap b = new System.Drawing.Bitmap(fileName);
System.Drawing.Size s = b.Size;
System.Windows.Media.ImageDrawing im = new System.Windows.Media.ImageDrawing();
im.Rect = new System.Windows.Rect(0, 0, s.Width, s.Height);
im.ImageSource = new System.Windows.Media.Imaging.BitmapImage(new Uri(fileName, UriKind.Absolute));
return im;
});
}
来自文档 (http://msdn.microsoft.com/en-us/library/dd997286.aspx):
Although you can write your own code to perform lazy initialization, we recommend that you use Lazy instead. Lazy and its related types also support thread-safety and provide a consistent exception propagation policy.
关于c# - 如何实现延迟位图加载?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8806220/