我正在开发一种需要位于App / config(Web.config)文件中的高级配置的工具。为实现这一点,我使用了自定义配置部分
App.config
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<section name="webConfiguration" type="MyConfigurationType, MyAssembly" />
</configSections>
<webConfiguration>
<requests>
<request name="Request-One">
<!-- details here, but they don't matter -->
</request>
<request name="Request-Two" basedOn="Request-One">
<!-- details here, but they don't matter -->
</request>
</requests>
</webConfiguration>
</configuration>
RequestElement.cs
public class RequestElement : ConfigurationElement
{
[ConfigurationProperty("name", IsKey = true, IsRequired = true)]
public string Name
{
get { return (string)base["name"]; }
set { base["name"] = value; }
}
[ConfigurationProperty("basedOn", IsRequired = false)]
public string BasedOn
{
get
{
return (string)this["basedOn"];
}
set
{
this["basedOn"] = value;
}
}
}
如您所见,这很简单。它正在编译和工作,没有例外。我要问的是,是否可以创建RequestElement
类型的配置属性并将其链接到正确的?(如下所示)
RequestElement.cs
public class RequestElement : ConfigurationElement
{
[ConfigurationProperty("name", IsKey = true, IsRequired = true)]
public string Name
{
get { return (string)base["name"]; }
set { base["name"] = value; }
}
[ConfigurationProperty("basedOn", IsRequired = false)]
public RequestElement BasedOn
{
get
{
return (RequestElement)this["basedOn"];
}
set
{
this["basedOn"] = value;
}
}
}
正如您所注意到的,Name
是一个密钥,因此在App.config
文件中使用名称会导致在打开ConfigurationManager
并获得正确的部分后,请求和任何请求,将能够使用BasedOn
属性访问真实对象。