首页 文章

在monodroid或monotouch中我应该使用什么而不是app.config来配置字符串?

提问于
浏览
15

我想在monodroid项目中存储开发与 生产环境 连接字符串和配置字符串 . 我通常将它作为应用程序设置存储在web.config或app.config中,但我应该如何在monodroid和monotouch项目中执行此操作?我也希望它能像调试工作室使用* .config文件一样在调试和发布版本之间自动切换配置 . 在iOS应用程序中,我可以将它们存储在plist中,但我想要一个单声道的跨平台解决方案 .

我如何在monodroid或monotouch中做到这一点?

2 回答

  • 5

    有一个以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:

    ConfigurationManager.Initialise(PCLAppConfig.FileSystemStream.PortableStream.Current);
    

    3)阅读您的设置: ConfigurationManager.AppSettings["config.text"];

  • 20

    您应该只使用带有 #if 声明的静态类 .

    就像是:

    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#代码完成工作 .

相关问题