【发布时间】:2014-08-22 11:51:53
【问题描述】:
使用System.Configuration,我如何识别子配置元素是完全丢失还是空的?
测试程序
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MissingConfigElementTest
{
class MyConfigurationElement : ConfigurationElement
{
[ConfigurationProperty("name")]
public string Name
{
get { return (string)base["name"]; }
}
}
class MyConfigurationSection : ConfigurationSection
{
[ConfigurationProperty("empty", DefaultValue = null)]
public MyConfigurationElement Empty
{
get { return (MyConfigurationElement)base["empty"]; }
}
[ConfigurationProperty("missing", DefaultValue = null)]
public MyConfigurationElement Missing
{
get { return (MyConfigurationElement)base["missing"]; }
}
}
class Program
{
static void Main(string[] args)
{
var configSection = (MyConfigurationSection)ConfigurationManager.GetSection("mySection");
Console.WriteLine("Empty.Name: " + (configSection.Empty.Name ?? "<NULL>"));
Console.WriteLine("Missing.Name: " + (configSection.Missing.Name ?? "<NULL>"));
Console.ReadLine();
}
}
}
测试配置
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<section name="mySection" type="MissingConfigElementTest.MyConfigurationSection, MissingConfigElementTest"/>
</configSections>
<mySection>
<empty />
</mySection>
</configuration>
输出
输出是
Empty.Name:
Missing.Name:
问题
我找不到一种方法来区分空的但存在的配置元素和整个配置元素被遗漏的情况。
我想要这个,因为如果一个元素存在,我想确保它通过某些验证逻辑,但完全不考虑元素也是可以的。
【问题讨论】:
标签: c# .net configuration configurationmanager