如何添加一个新的属性,以Properties.Settings?(How do I add a ne

2019-10-19 03:44发布

我想一个新的属性在运行时添加到Properties.Settings,但我不知道这是如何工作。 语言:C#我用这个代码:

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异常。

Answer 1:

这是不够的,设置属性名。 你也应该至少定义属性的属性和设置提供商。 设置此信息最简单的方法是使用现有财产的信息。 例如,如果你已经在使用,从文件中读取/存储属性值的设置,你还打算使用配置文件中的解决方案如下:

        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);

在你需要一些新的东西的话,你可以找到示例代码在这里 。



文章来源: How do I add a new Property to Properties.Settings?