如何将新的属性添加到Properties.Settings? [英] How do I add a new Property to Properties.Settings?

查看:649
本文介绍了如何将新的属性添加到Properties.Settings?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在运行时向Properties.Settings添加一个新的Property,但是我不知道它是如何工作的.语言:c# 我使用了以下代码:

I want to add a new Property to Properties.Settings at runtime, but I don't know how this works. Language: c# I used this Code:

Properties.Settings.Default.Properties.Add(new System.Configuration.SettingsProperty(serviceName + "VersionsNr"));
Properties.Settings.Default.Save();

Properties.Settings.Default[serviceName + "VersionsNr"] = versionsNr;
Properties.Settings.Default.Save();

我得到一个NullReferenceException.

I get an NullReferenceException.

推荐答案

仅设置属性名称是不够的.您还应该至少定义属性属性和设置提供程序.设置此信息的最简单方法是使用现有属性中的信息.例如,如果您已经使用了从文件读取/存储属性值的设置,并且还打算使用配置文件,则解决方案如下:

It's not enough to set property name. You should also define at least property attributes and setting provider. The simplest method to set this info is to use the information from existing property. For example, if you already use Settings that read/store properties values from file and you also intend use the configuration file the solution will be as follows:

        var existingProperty = Settings.Default.Properties["<existing_property_name>"];
        var property = new System.Configuration.SettingsProperty(
            "<new_property_name>",
            typeof(string),
            existingProperty.Provider,
            false,
            null,
            System.Configuration.SettingsSerializeAs.String,
            existingProperty.Attributes,
            false,
            false);
        Settings.Default.Properties.Add(property);

如果您需要新的东西,可以找到示例代码这里.

In the case you need something new, you can find sample code here.

这篇关于如何将新的属性添加到Properties.Settings?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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