gpt4 book ai didi

c# - 如何识别缺少的 ConfigurationElement?

转载 作者:行者123 更新时间:2023-12-02 08:32:14 24 4
gpt4 key购买 nike

使用 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:

问题

我找不到一种方法来区分空的但存在的配置元素和整个配置元素被遗漏的情况。

我想要这个是因为如果存在一个元素,我想确保它通过特定的验证逻辑,但完全不包含该元素也很好。

最佳答案

此外,ElementInformation.IsPresent属性可用于确定元素是否存在于原始配置中。

var configSection = ( MyConfigurationSection ) ConfigurationManager.GetSection( "mySection" );

Console.WriteLine( "Empty.Name: " + ( configSection.Empty.ElementInformation.IsPresent ? configSection.Empty.Name : "<NULL>" ) );
Console.WriteLine( "Missing.Name: " + ( configSection.Missing.ElementInformation.IsPresent ? configSection.Missing.Name : "<NULL>" ) );

Console.ReadLine( );

这将输出

Empty.Name:
Missing.Name: <NULL>

关于c# - 如何识别缺少的 ConfigurationElement?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25446364/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com