//设置键值 Preferences.Set("user", "admin"); //设置user的值为admin //读取键值 var user = Preferences.Get("user","superAdmin"); //读取key为"user"的值,如果没有,返回"superAdmin" //判断是否含有键 bool exist = Preferences.ContainsKey("user"); //是否含有"user"键 //删除键 Preferences.Remove("user"); 删除user
Preferences Manager会自动将set的数据永久保存起来,也就是说,当你重新启动APP后,还能找回上次设置的值。
这个特性可以将其作为一个配置管理器使用。比如以下用法基于Preferences Manager构建了一个ISettingsService接口和SettingsService类,以实现依赖注入功能
//ISettingsServices.cs public interface ISettingsService { string ApiUrl { get; set; } string AccessToken { get; set; } string Gongxu { get; set; } string EmployeeNo { get; set; } }
public class SettingsService : ISettingsService { public string ApiUrl { get => Preferences.Get("apiUrl", "http://localhost:5566/api"); set => Preferences.Set("apiUrl", value); } public string AccessToken { get => Preferences.Get("access_token",string.Empty); set => Preferences.Set("access_token", value); } public string Gongxu { get => Preferences.Get("gongxu", "GX888"); set => Preferences.Set("gongxu", value); } public string EmployeeNo { get => Preferences.Get("employeeNo", "88888"); set => Preferences.Set("employeeNo", value); } }