繁体   English   中英

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

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

第一次(在设置之前)读取设置会抛出Object reference not set to an instance of an object.Object reference not set to an instance of an object. 例外。

在实际情况下,无法使用DefaultSettingValueAttribute设置默认值,因为它不是像我的int示例中那样的简单类型,并且不能描述为字符串。 文档

DefaultSettingValueAttribute要求默认值可以表示为字符串。

如何避免这种情况?

更多信息:

当然,我可以将其包装在try-catch块中,但是在特殊情况下应该保留它,这是正常现象-首次使用该应用程序的每个用户都会遇到此问题。 try每次try因为第一次似乎是错误的。

那么正确的解决方案是什么?

这是代码:

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; }
    }
}

并这样称呼:

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

您需要指定设置的默认值。 我认为应该防止它出现在内存中。

如果您不能指定默认值,请在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