在Contructor中初始化后,C#静态成员变为null

时间:2015-09-21 13:28:13

标签: c# static bitmapimage

我有一个包含静态ImageSource对象的类,这些对象以后经常被其他类访问:

public class ImagePrepare
{
    public static readonly ImageSource m_imageGreen;
    public static readonly ImageSource m_imageYellow;
    public static readonly ImageSource m_imageRed;
    public static readonly ImageSource m_imagePurple;

    public static int iTest;

    //static Constructor
    static ImagePrepare()
    {
        iTest = 2;

        Uri uriImage = new Uri("pack://application:,,,/" + Assembly.GetExecutingAssembly().GetName().Name + ";component/" + "Ressourcen/Button_Green.png", UriKind.Absolute);
        ImageSource m_imageGreen = new BitmapImage(uriImage);

        uriImage = new Uri("pack://application:,,,/" + Assembly.GetExecutingAssembly().GetName().Name + ";component/" + "Ressourcen/Button_Yellow.png", UriKind.Absolute);
        ImageSource m_imageYellow = new BitmapImage(uriImage);

        uriImage = new Uri("pack://application:,,,/" + Assembly.GetExecutingAssembly().GetName().Name + ";component/" + "Ressourcen/Button_Red.png", UriKind.Absolute);
        ImageSource m_imageRed = new BitmapImage(uriImage);

        uriImage = new Uri("pack://application:,,,/" + Assembly.GetExecutingAssembly().GetName().Name + ";component/" + "Ressourcen/Button_Purple.png", UriKind.Absolute);
        ImageSource m_imagePurple = new BitmapImage(uriImage);
    }

    public static ImageSource GetImageSource()
    {
        return m_imageGreen;
    }
}

现在,当我从MainWindow类调用ImagePrepare.GetImageSource()时,首先调用静态ctor,并按照假设正确初始化所有静态成员。
然后调用GetImageSource(),但在调试此函数时,成员m_imageGreen为null!
我在这里想念的是什么? 成员iTest的行为与假设一样,仍然保持其值为2。

1 个答案:

答案 0 :(得分:8)

在静态构造函数中,您将静态成员重载为本地成员。

通过调用:

ImageSource m_imageGreen = new BitmapImage(uriImage);

实际上,您创建了一个新的局部变量,而不是引用静态变量。 这样做:

m_imageGreen = new BitmapImage(uriImage);