C#中如何检查静态对象是否为空?解决SettingsViewModel空引用异常问题
解决C#静态对象空引用异常及Endpoint检查问题
你遇到的Object reference not set to an instance of an object异常,核心原因很明确:你的静态settingsViewModel对象本身还没有被实例化,就直接去访问它的Endpoint属性了。静态字段在默认情况下初始值是null,所以直接调用settingsViewModel.Endpoint必然会触发空引用错误。
下面给你几个可行的解决方案,适配应用启动阶段的场景:
1. 先检查静态对象是否为null,再判断Endpoint
修改你的判断逻辑,先确保settingsViewModel实例存在,再去检查它的属性。利用C#的短路逻辑(||左边为true时,右边不会执行),避免空引用:
public App() { InitializeComponent(); if (UseMockDataStore) DependencyService.Register<MockDataStore>(); MainPage = new AppShell(); // 先检查对象是否存在,再检查Endpoint if (settingsViewModel == null || string.IsNullOrEmpty(settingsViewModel.Endpoint)) { Shell.Current.DisplayAlert("Endpoint Not Found", "There's no endpoint found in settings, please enter a valid endpoint", "OK"); } }
2. 提前初始化静态对象
你可以在声明静态属性的时候直接完成实例化,或者在App构造函数里先确保对象存在:
方式一:声明时初始化
// 直接在声明时实例化静态对象 public static SettingsViewModel settingsViewModel { get; set; } = new SettingsViewModel(); public App() { InitializeComponent(); if (UseMockDataStore) DependencyService.Register<MockDataStore>(); MainPage = new AppShell(); // 现在可以安全访问Endpoint了 if (string.IsNullOrEmpty(settingsViewModel.Endpoint)) { Shell.Current.DisplayAlert("Endpoint Not Found", "There's no endpoint found in settings, please enter a valid endpoint", "OK"); } }
方式二:构造函数中懒加载初始化
使用空合并赋值运算符??=,只有当settingsViewModel为null时才实例化:
public static SettingsViewModel settingsViewModel { get; set; } public App() { InitializeComponent(); // 确保静态对象已实例化 settingsViewModel ??= new SettingsViewModel(); if (UseMockDataStore) DependencyService.Register<MockDataStore>(); MainPage = new AppShell(); if (string.IsNullOrEmpty(settingsViewModel.Endpoint)) { Shell.Current.DisplayAlert("Endpoint Not Found", "There's no endpoint found in settings, please enter a valid endpoint", "OK"); } }
3. 从持久化存储加载设置(更符合Settings场景)
既然是SettingsViewModel,通常应该从本地持久化存储(比如Xamarin/.NET MAUI的Preferences)加载配置,而不是直接new一个空对象。这样既能避免空引用,又能保留用户之前保存的设置:
public static SettingsViewModel settingsViewModel { get; set; } public App() { InitializeComponent(); // 从本地偏好设置加载Endpoint,默认值为空字符串 settingsViewModel = new SettingsViewModel { Endpoint = Preferences.Get("Endpoint", string.Empty) }; if (UseMockDataStore) DependencyService.Register<MockDataStore>(); MainPage = new AppShell(); if (string.IsNullOrEmpty(settingsViewModel.Endpoint)) { Shell.Current.DisplayAlert("Endpoint Not Found", "There's no endpoint found in settings, please enter a valid endpoint", "OK"); } }
后续用户设置了Endpoint后,记得用Preferences.Set("Endpoint", settingsViewModel.Endpoint)保存到本地,下次启动就能直接加载。
内容的提问来源于stack exchange,提问作者Kalindu
相关产品推荐
相关产品推荐

