用作图片缓冲区的C#Singleton
我想使用单例模式来创建一个缓冲区,在那里存储所有需要的图片 诸如此类:用作图片缓冲区的C#Singleton,c#,memory,reference,singleton,C#,Memory,Reference,Singleton,我想使用单例模式来创建一个缓冲区,在那里存储所有需要的图片 诸如此类: public sealed class BaseBuffer { private static readonly Dictionary<string, Bitmap> pictures = new Dictionary<string, Bitmap>(); public static Bitmap GetPicture(string name, ref Bitmap output)
public sealed class BaseBuffer
{
private static readonly Dictionary<string, Bitmap> pictures = new Dictionary<string, Bitmap>();
public static Bitmap GetPicture(string name, ref Bitmap output)
{
//In case the pictureBuffer does not contain the element already
if (!pictures.ContainsKey(name))
{
//Try load picture from resources
try
{
Bitmap bmp = new Bitmap(System.Reflection.Assembly.GetEntryAssembly().GetManifestResourceStream("MyProject.Resources." + name + ".png"));
pictures.Add(name, bmp);
return bmp;
}
catch (Exception ex)
{
Console.WriteLine("Picture {0} cannot be found.", name);
}
}
else
{
return pictures[name];
}
return null;
}
公共密封类基缓冲区
{
私有静态只读字典图片=新建字典();
公共静态位图GetPicture(字符串名称,参考位图输出)
{
//如果pictureBuffer尚未包含该元素
如果(!pictures.ContainsKey(名称))
{
//尝试从资源中加载图片
尝试
{
位图bmp=新位图(System.Reflection.Assembly.GetEntryAssembly().GetManifestResourceStream(“MyProject.Resources.”+name+“.png”);
图片。添加(名称,bmp);
返回bmp;
}
捕获(例外情况除外)
{
WriteLine(“找不到图片{0}。”,名称);
}
}
其他的
{
返回图片[名称];
}
返回null;
}
现在我不确定,“GetPicture”方法是返回图片的副本还是返回引用
应用程序将需要一些图片,这些图片经常显示在不同的应用程序/表单上。因此,最好只引用这些图片,而不是复制它们
你知道怎么做吗?我不确定,但是我想你应该做
output=bmp;
等等,而不是return bmp;
。否则你可以去掉这个参数
我还认为,即使
返回bmp;
等等,也会返回一个引用,但不会返回存储在dict中的位图的副本。因此,无论哪种方法都可以……它都会返回对位图的引用(因为它被定义为类)保留在字典中。因此不,它不会返回不同的副本。对返回的位图的更改也将在字典中观察,因为它们将是相同的基础对象。我不确定您对ref位图输出做了什么,因为它似乎未被使用
此外,如果经常调用,字典上的TryGetValue
的性能会稍好一些:
Bitmap bmp;
if (!pictures.TryGetValue(name, out bmp))
{
bmp = new Bitmap(System.Reflection.Assembly.GetEntryAssembly().GetManifestResourceStream("MyProject.Resources." + name + ".png"));
pictures.Add(name, bmp);
}
return bmp;
很抱歉,“输出位图”只是一次尝试(返回vs输出),但我更喜欢返回。复制粘贴错误;-)谢谢您提供的信息/提示。