第一次读取设置(已经设置了-before)会引发Object reference not set to an instance of an object.异常。
在实际情况下,不能使用DefaultSettingValueAttribute设置默认值,因为它不是像我的int示例中那样简单的类型,也不能描述为字符串。来自医生们
DefaultSettingValueAttribute要求默认值可以表示为字符串。
如何避免这种情况呢?
更多信息:
当然,我可以将它封装在try-catch块中,但这应该留待特殊情况使用,而这是一件正常的事情--每个首次使用应用程序的用户都会遇到这种情况。而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;发布于 2013-07-30 19:32:29
您需要为该设置指定一个默认值。我认为这应该能阻止它从记忆中消失。
如果不能指定默认值,请在getter中检查它是否为null,是否将其初始化为您自己的默认值。
get {
if(this["MyInt"] == null)
this["MyInt"] = 0;
return (int)(this["MyInt"]);
}https://stackoverflow.com/questions/17955728
复制相似问题