【问题标题】:C# Singleton used as a picture bufferC# Singleton 用作图片缓冲区
【发布时间】:2013-12-11 09:11:14
【问题描述】:

我想使用单例模式来创建一个缓冲区来存储所有需要的图片。

类似的东西:

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”方法是返回图片的副本还是返回引用?

应用程序需要一些图片,这些图片经常在不同的应用程序/表单上显示。因此,最好只引用图片而不是复制它们。

你知道怎么做吗?

【问题讨论】:

    标签: c# memory reference singleton


    【解决方案1】:

    它将返回对字典中保存的Bitmap(因为它被定义为一个类)的引用。所以不,它不会返回一个不同的副本。返回的位图的更改也将在字典中观察到,因为它们将是相同的底层对象。我不确定你在用你的ref Bitmap output 做什么,因为它似乎没有被使用。

    此外,如果经常调用,字典中的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;
    

    【讨论】:

    • 对不起,“输出位图输出”只是一次尝试(返回与输出),但我更喜欢返回。复制粘贴错误;-) 感谢您提供信息/提示。
    【解决方案2】:

    对此我不确定,但我猜你应该做return bmp; 而不是output=bmp; 等等。否则你可以摆脱参数。

    我还认为,即使 return bmp; 等也会返回引用,但不会返回存储在字典中的 Bitmap 的副本。所以无论哪种方式都可以......

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-02-20
      • 2012-04-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-11-14
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多