如何保存/序列化自定义类的设置文件? [英] How do I save/serialize a custom class to the settings file?

查看:152
本文介绍了如何保存/序列化自定义类的设置文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个小的类,用于保存两个字符串如下:

I have a small class that holds two strings as follows:

    public class ReportType
    {
        private string displayName;
        public string DisplayName
        {
            get { return displayName; }
        }

        private string reportName;
        public string ReportName
        {
            get { return reportName; }
        }

        public ReportType(string displayName, string reportName)
        {
            this.displayName = displayName;
            this.reportName = reportName;
        }
    }

我想这个类的一个实例保存到我的设置文件,这样我可以做到以下几点:

I want to save an instance of this class to my settings file so that I can do the following:

ReportType reportType = Settings.Default.SelectedReportType;

谷歌搜索似乎表明,这是可能的,但似乎没有成为一个明确的指导任何地方我跟着。据我所知,一些序列化是必需的,但真的不知道从哪里开始。此外,当我去到Visual Studio中的设置屏幕,然后单击浏览类型列下没有选项来选择包含类的ReportType当前的命名空间。

Googling seems to suggest that it is possible but there doesn't appear to be a clear guide anywhere for me to follow. I understand that some serialization is required but don't really know where to begin. Also, when I go into the Settings screen in Visual Studio and click "browse" under the Type column there is no option to select the current namespace which contains the ReportType class.

推荐答案

确定我想我最终算出来。要做的第一件事就是把下面的属性添加到需要被序列化和ApplicationSettingsBase继承类类的ReportType的每个属性:

OK I think that I have eventually worked it out. The first thing to do is to add the following attributes to each property of the ReportType class that needs to be serialised and inherit the class from ApplicationSettingsBase:

    public class ReportType : ApplicationSettingsBase
    {
        private string displayName;
        [UserScopedSetting()]
        [SettingsSerializeAs(System.Configuration.SettingsSerializeAs.Xml)]
        public string DisplayName
        {
            get { return displayName; }
        }

..............

..............

然后,一旦你已经重建的组件(重要!),你可以进入设置界面,点击浏览,然后在底部(例如Label_Cre​​ator.ReportType)文本框中键入您的命名空间和类名。命名空间和类名的显示在树中,因此这部分是不完全明显,你需要做的这就是为什么它是一个有点混乱什么....

and then, once you have rebuilt your assembly (important!) you can go into the settings screen and click browse and then type your namespace and class name in the text box at the bottom (e.g. Label_Creator.ReportType). The namespace and class name do not appear in the tree and so this part is not exactly obvious what you need to do which is why it is a bit confusing....

这篇关于如何保存/序列化自定义类的设置文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆