簡體   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