c#静态成员在构造函数中初始化后得到null

本文关键字:null 初始化 静态成员 构造函数 | 更新日期: 2023-09-27 18:13:57

我有一个类保存静态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()时,首先调用静态函数,并按预期正确初始化所有静态成员。
然后调用GetImageSource(),但是在调试该函数时,成员m_imageGreen为空!
我遗漏了什么?
成员iTest的行为与预期一样,仍然保持其值2。

c#静态成员在构造函数中初始化后得到null

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

通过调用

:

ImageSource m_imageGreen = new BitmapImage(uriImage);

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

m_imageGreen = new BitmapImage(uriImage);