public static class Configuration {
#if DEBUG
public const string ConnectionString = "debug string";
#else
public const string ConnectionString = "release string";
#endif
}
使用 app.config 的好处是能够在不重新编译的情况下更改文件系统上的这些设置 . 在移动设备上,没有部署't a good way (especially on iOS) to edit the file after it' . 因此,只需使用静态类并在需要更改值时重新部署通常会更好 . 这也适用于所有平台,因为它只是C#代码完成工作 .
2 回答
有一个以Xamarin为中心的AppSetting阅读器,可在https://www.nuget.org/packages/PCLAppConfig获得,它对于持续交付非常有用;
按以下方式使用:
1)将nuget包引用添加到您的pcl和平台项目中 .
2)在PCL项目中添加app.config文件,然后在所有平台项目上添加链接文件 . 对于android,请确保将构建操作设置为'AndroidAsset',对于UWP,将构建操作设置为'Content' . 添加设置键/值:
<add key="config.text" value="hello from app.settings!" />
3)在你的每个平台项目上初始化ConfigurationManager.AppSettings,就在'Xamarin.Forms.Forms.Init'语句之后,在iOS中的AppDelegate,Android中的MainActivity.cs,UWP / Windows 8.1 / WP 8.1中的App:
3)阅读您的设置:
ConfigurationManager.AppSettings["config.text"];
您应该只使用带有
#if
声明的静态类 .就像是:
使用
app.config
的好处是能够在不重新编译的情况下更改文件系统上的这些设置 . 在移动设备上,没有部署't a good way (especially on iOS) to edit the file after it' . 因此,只需使用静态类并在需要更改值时重新部署通常会更好 . 这也适用于所有平台,因为它只是C#代码完成工作 .