는 enum
포함이 샘플 ConfigurationSection
감안할 때 : (. System.ComponentModel.DataAnnotations
필요)를 enum
값이 유효하지 않은 경우이 예외가 발생합니다
public class MyConfigurationSection : ConfigurationSection
{
[ConfigurationProperty(name: "myProperty")]
public TestEnum MyProperty =>
(TestEnum) Enum.Parse(typeof(TestEnum), Convert.ToString(base["myProperty"]));
}
public enum TestEnum
{
A = 1, B = 2
}
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<section name="myConfigurationSection"
type="ValidatedConfigurationSection.MyConfigurationSection,
ValidatedConfigurationSection"/>
</configSections>
<myConfigurationSection myProperty="NoSuchValueInEnum"/>
</configuration>
을
private void ValidateSection(object section)
{
var context = new ValidationContext(section);
Validator.ValidateObject(section, context);
}
개체 자체에 대한 유효성 검사 특성은 필요하지 않습니다.
응용 프로그램 시작시 각 사용자 지정 섹션을로드하고 유효성을 검사 할 수 있습니다. 로드하려고하면 예외가 발생하거나 유효하지 않다고 판단되는 다른 값이 포함됩니다. –
문제는 이제 사용자 지정 섹션의 특정 속성에 액세스하려고 시도 할 때까지 예외가 throw됩니다. 좀 더 자동화 된 방법으로 트릭을하지 않는 한 그렇게 쉬운 일은 아닙니다. –
[데이터 주석] (https://msdn.microsoft.com/en-us/library/system.componentmodel.dataannotations (v = vs.110) .aspx)을 사용하여 사용자 지정 구성 클래스를 마크 업하고 유효성을 검사 할 수 있습니다. 유효성 검사가 아무 것도하지 않더라도 속성에 대한 액세스가 강제로 이루어지면 차례대로 예외가 throw됩니다. –