简体   繁体   English

公共静态类中使用公共静态变量时的异常

[英]exception when using public static variables in public static class

After I made a public static class has some public static variables when I tried to use one of static variables VS had an exception The type initializer for 'EM_Image.staticvariables' threw an exception. 当我尝试使用其中一个静态变量时,使一个公共静态类具有一些公共静态变量后,VS发生了异常。'EM_Image.staticvariables'的类型初始值设定项引发了异常。

Why? 为什么? and how I can solve it? 以及我该如何解决?

public static class StaticVariables
{
    public static string image_source = "ahmed";
    public static Bitmap b            = new Bitmap(image_source);
    public static int K_numcolors     = 0;
    public static int M_leastbits     = 0;
    public static BitmapImage bi      = null;

    public static Color[,] RGB_num         = new Color[b.Width, b.Height];     // orginal colors
    public static Color[,] new_RGB_byte    = new Color[b.Width, b.Height];     // colors after compression 1
    public static string[,,] RGB_Bits      = new string[b.Width, b.Height, 3]; // original images
    public static string[,,] new1_RGB_Bits = new string[b.Width, b.Height, 3]; // after compression 1
}
private void bt_Browse_Click(object sender, System.Windows.RoutedEventArgs e)
{
    browse.ShowDialog();
    direction_text.Text = browse.FileName;
    staticvariables.image_source = browse.FileName;
    ImageSource imageSource = new BitmapImage(new Uri(browse.FileName));
    pic_origin.Source = imageSource;
}

Edit: 编辑:

public static string image_source="ahmed" ;
public static Bitmap b=new Bitmap(image_source);

Looks like your default image_source is creating a null Bitmap - so the exception is thrown when the other static properties are initialized and try to access Bitmap b - which is null: 貌似默认image_source是创建一个null的位图-所以,当其他静态属性初始化,然后尝试访问抛出异常Bitmap b -这是空:

public static Color[,] RGB_num = new Color[b.Width, b.Height];//orginal colors

Your current design doesn't really suit your needs - it looks like you need a singleton instance instead of a collection of static properties. 您当前的设计并不能真正满足您的需求-似乎您需要一个单例实例,而不是静态属性的集合。 Having said that, you can just initialize all variables with null (all those Color variables ie) and once you have valid input ie image_source ) you have to update/initialize them all. 话虽这么说,您可以只使用null初始化所有变量(所有Color变量,即),并且一旦输入有效,即image_source ,就必须更新/初始化所有变量。

The code that initializes your class (in the initializers for the fields or in a static constructor) threw an exception. 初始化类的代码(在字段的初始化程序中或在静态构造函数中)引发了异常。

You can see the actual exception in the InnerException property, or by telling the debugger to break whenever an exception is thrown in Debug, Exceptions. 您可以在InnerException属性中看到实际的InnerException ,也可以通过告诉调试器在Debug Exceptions中抛出异常时中断。

I solved it by changing my static variables with assignments: 我通过分配静态变量来解决它:

public static string image_source = "ahmed" ;
public static Bitmap b=new Bitmap(image_source);

Using properties: 使用属性:

public static string image_source { get; set; }
public static Bitmap b=new Bitmap { get; set; }

I did have to initialize the values at run time, but didn't see that as a problem. 我确实必须在运行时初始化这些值,但并没有将其视为问题。

Why 为什么

Whenever first time we use a static class, that class gets initialized. 每当我们第一次使用静态类时,该类都会被初始化。 So when you set the static field 因此,当您设置静态字段时

staticvariables.image_source

before the field is set, your class "staticvariables" gets initialized, while initializing it sets "image_source" to "ahmed". 在设置字段之前,将初始化您的类“ staticvariables”,而在初始化该类时会将“ image_source”设置为“ ahmed”。

In the next line the constructor of Bitmap class will throw, "ArgumentException" and that is why your "staticvariables" class will stop code execution that point itself, and @BrokenGlass the value of Bitmap b will not be null for other statements. 在下一行中,Bitmap类的构造函数将引发“ ArgumentException”,这就是为什么您的“ staticvariables”类将停止执行指向自身的代码的原因,而@BrokenGlass对于其他语句,Bitmap b的值将不为null。 The exception will stop the code execution. 异常将停止代码执行。

During class initialization if any exception occurs, the "TypeInitializationException" will be created and the actual exception will be set as InnerException property, which in this case will be ArgumentException: "Parameter is not valid". 在类初始化期间,如果发生任何异常,将创建“ TypeInitializationException”,并将实际异常设置为InnerException属性,在这种情况下,该属性将为ArgumentException:“参数无效”。

How to solve 怎么解决

By looking at your bt_Browse_Click, it seems you want user to select the image file. 通过查看您的bt_Browse_Click,似乎您希望用户选择图像文件。 and may be at that time only you need to set other fields of the static class. 并且可能只有那时您需要设置静态类的其他字段。

So below implementation of your "staticvariables" should give you an idea... Please note I have changed the class name to Pascal case. 因此,在下面的“ staticvariables”实现中应该可以给您一个思路...请注意,我已将类名称更改为Pascal大小写。

public static class StaticVariables
{
    public static string _image_source = "ahmed";

    public static string image_source 
    {
        get => _image_source;
        set 
        {
            if (!File.Exists(value))
            {
                throw new FileNotFoundException();
            }
            _image_source = value;
            SetImageData();
        }
    }

    public static Bitmap b = null;
    public static int K_numcolors = 0;
    public static int M_leastbits = 0;
    public static BitmapImage bi = null;
    public static Color[,] RGB_num = null;//orginal colors
    public static Color[,] new_RGB_byte = null;// colors after compression 1
    public static string[, ,] RGB_Bits = null;//original images
    public static string[, ,] new1_RGB_Bits = null;//after compression 1

    private static void SetImageData()
    {
        b = new Bitmap(_image_source);
        RGB_num = new Color[b.Width, b.Height];//orginal colors
        new_RGB_byte = new Color[b.Width, b.Height];// colors after compression 1
        RGB_Bits = new string[b.Width, b.Height, 3];//original images
        new1_RGB_Bits = new string[b.Width, b.Height, 3];//after compression 1
    }
}

Regarding whether or not to use Singleton pattern, Jon Skeet has already given answer, about the difference between Singleton pattern implementation and static class. 关于是否使用Singleton模式,Jon Skeet已经就Singleton模式实现与静态类之间的区别给出了答案。 However for now you should go with simple things. 但是,现在您应该处理简单的事情。

Hope it helps. 希望能帮助到你。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM