【发布时间】:2018-07-02 07:06:51
【问题描述】:
我花了几个星期试图弄清楚这一点,这是我之前提出的一个问题的重复,但没有得到答复,所以我在这里完善这个问题。
我创建了一个自定义类:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Collections;
using System.Configuration;
namespace mssql_gui
{
public class TestConfigSection : ConfigurationSection
{
[ConfigurationProperty("", IsRequired = true, IsDefaultCollection = true)]
public TestConfigInstanceCollection Instances
{
get { return (TestConfigInstanceCollection)this[""]; }
set { this[""] = value; }
}
}
public class TestConfigInstanceCollection : ConfigurationElementCollection
{
protected override ConfigurationElement CreateNewElement()
{
return new TestConfigInstanceElement();
}
protected override object GetElementKey(ConfigurationElement element)
{
return ((TestConfigInstanceElement)element).Key;
}
}
public class TestConfigInstanceElement : ConfigurationElement
{
[ConfigurationProperty("key", IsKey = true, IsRequired = true)]
public string Key
{
get { return (string)base["key"]; }
set { base["key"] = value; }
}
[ConfigurationProperty("value", IsRequired = true)]
public string Value
{
get { return (string)base["value"]; }
set { base["value"] = value; }
}
}
}
我已经实现了:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<configSections>
<section name="testSection" type="mssql_gui.TestConfigSection"/>
</configSections>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6.1"/>
</startup>
<appSettings>
<add key="Data Source" value="localhost\SQLEXPRESS"/>
<add key="Initial Catalog" value="(empty)"/>
<add key="Integrated Security" value="SSPI"/>
</appSettings>
<testSection>
<add key ="testKey" value="tesValue"/>
</testSection>
</configuration>
我已经尝试访问它,我得到:
为 testSection 创建配置节处理程序时出错:无法从程序集“System.Configuration, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a”加载类型“mssql_gui.TestConfigSection”。
我知道在类型中,我应该声明一个程序集 dll,但我对此感到困惑......因为在 official instructions by MS 中,它说要为处理程序创建一个新类:
创建一个继承自 System.Configuration.ConfigurationSection 类。
添加代码以定义部分的属性和元素。
添加类(至少通过 Visual Studio 界面)会创建一个 .cs 文件,而不是 .dll 程序集文件,因此如何将该自定义类添加到程序集文件中以便在 <configSections> 中引用它app.config 的一部分?
【问题讨论】:
标签: c# .net app-config