本文介绍了.NET中的自定义配置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我看到有关.NET中自定义配置的简单示例。我的情况有点复杂,有嵌套的节点。
I am seeing simple examples regarding custom configuration in .NET. My case is a bit more complex, with nested nodes.
我想从配置文件中读取这个:
I'd like to be able to read this from the configuration file:
<environments>
<environment name="live" url="http://www.live.com">
<server name="a" IP="192.168.1.10"></server>
<server name="b" IP="192.168.1.20"></server>
<server name="c" IP="192.168.1.30"></server>
</environment>
<environment name="dev" url="http://www.dev.com">
<server name="a" IP="192.168.1.10"></server>
<server name="c" IP="192.168.1.30"></server>
</environment>
<environment name="test" url="http://www.test.com">
<server name="b" IP="192.168.1.20"></server>
<server name="d" IP="192.168.1.40"></server>
</environment></environments>
如果任何人可以提供一些代码,我会很感激。
If anyone could provide some code for that, I'd appreciate it.
谢谢!
推荐答案
您可以通过实现从ConfigurationElement类继承的自定义配置类
You can read this by implementing custom configuration classes inheriting from the ConfigurationElement class.
以下是server元素的示例:
Here is an example of the "server" element:
public class ServerElement: ConfigurationElement
{
[ConfigurationProperty("name", IsRequired = true, IsKey = true)]
public string Name
{
get { return ((string)base["name"]); }
set { base["name"] = value; }
}
...
}
环境元素实际上是一个集合,可以像这样实现:
The environment element is actually a collection and could be implemented like this:
public class EnvironmentElement: ConfigurationElementCollection
{
protected override ConfigurationElement CreateNewElement(string elementName)
{
return new ServerElement(...);
}
}
这篇关于.NET中的自定义配置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!