简体   繁体   English

首次使用时自定义设置类异常(ApplicationSettingsBase)

[英]Custom Settings-class exception on first use (ApplicationSettingsBase)

Reading the Settings for the first time (-before they've been set) throws an Object reference not set to an instance of an object. 第一次(在设置之前)读取设置会抛出Object reference not set to an instance of an object.Object reference not set to an instance of an object. exception. 例外。

Setting a default value using DefaultSettingValueAttribute cannot be done in the real case because it's not a simple type like in the my example of an int, and can't be described as a string. 在实际情况下,无法使用DefaultSettingValueAttribute设置默认值,因为它不是像我的int示例中那样的简单类型,并且不能描述为字符串。 From the docs : 文档

DefaultSettingValueAttribute requires that the default value can be represented as a string. DefaultSettingValueAttribute要求默认值可以表示为字符串。

How should this be avoided? 如何避免这种情况?

More info: 更多信息:

Of course I can wrap it in a try-catch block, but that should be left for exceptional cases, whereas this is a normal thing - every user who will use the application for the first time will encounter this. 当然,我可以将其包装在try-catch块中,但是在特殊情况下应该保留它,这是正常现象-首次使用该应用程序的每个用户都会遇到此问题。 And try ing every time because of that first time seems wrong. try每次try因为第一次似乎是错误的。

So what's the correct solution? 那么正确的解决方案是什么?

Here's the code: 这是代码:

public class MySettings : ApplicationSettingsBase
{
    [UserScopedSettingAttribute()]
    public int MyInt
    {
        get { return (int)(this["MyInt"]); } // Object reference not set to an instance of an object.
        set { this["MyInt"] = value; }
    }
}

And called so: 并这样称呼:

MySettings s = new MySettings();
int i = s.MyInt;

You need to specify a default value for the setting. 您需要指定设置的默认值。 I think that should prevent it from memory. 我认为应该防止它出现在内存中。

If you can't specify a default, put a check in the getter to see if its null, if it is initialize it to your own default value. 如果您不能指定默认值,请在getter中进行检查,以查看其是否为null(如果已将其初始化为您自己的默认值)。

get { 

      if(this["MyInt"] == null)
          this["MyInt"] = 0;

      return (int)(this["MyInt"]); 
    }

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

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