我已经花了几周的时间来尝试解决这个问题,这是我之前提出的一个问题的重复,但没有得到回应,所以我在这里进行了问题的精炼。
我创建了一个自定义类:
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,但我对此感到困惑……因为在MS的官方说明中,它说要为处理程序创建一个新类:
创建一个公共类,该类继承自 System.Configuration.ConfigurationSection 类。
添加代码以定义部分的属性和元素。
添加该类(至少通过 Visual Studio 界面)会创建一个 .cs 文件,而不是 .dll 程序集文件,那么我该如何将该自定义类添加到程序集文件中,以便在 app.config 的 <configSections>
部分中引用它?