2009-02-20 6 views
13

지난 3 일 동안 인터넷을 수색 했으므로이 질문에 대한 참조를 찾을 수 없습니다. 내 app.config와 함께 사용할 사용자 지정 구성 클래스를 만들었습니다. 모든 것이 잘 작동합니다. 구성 요소의 구성 등록 정보가 필요하지 않고 app.config에 정의되지 않은 경우 문제가 발생합니다. 구성 속성에 대해 기본값이 반환되는 것 같습니다. 누구든지 속성이 app.config에 정의되어 있지 않은지 확인하는 방법을 알고 있습니까? (내의 app.config를 게시하려고 노력했지만, 그것을 수행하는 방법을 알아낼 수 없습니다 ... 사람이 어떻게 알아?) 난의 상단 떨어져 생각할 수사용자 지정 구성, ConfigurationElements 및 ConfigurationProperties


//Main 
namespace TestStub 
{ 
    class Program 
    { 
     static void Main(string[] args) 
     { 
      CustomSettingsHandler config = (CustomSettingsHandler)ConfigurationManager.GetSection("CustomSettingsManager"); 
      Console.WriteLine("Setting1 {0}", config.Setting1.CustomSettingItem); 
      Console.WriteLine("Setting2 {0}", config.Setting2.CustomSettingItem); 
     } 
    } 
} 

//Custom Configuration Class 
namespace CustomConfiguration 
{ 
    public class CustomSettingsHandler : ConfigurationSection 
    { 
     [ConfigurationProperty("setting1", IsRequired = false)] 
     public CustomSettingElement Setting1 { get { return (CustomSettingElement)this["setting1"]; } } 

     [ConfigurationProperty("setting2", IsRequired = false)] 
     public CustomSettingElement Setting2 { get { return (CustomSettingElement)this["setting2"]; } } 
    } 

    public class CustomSettingElement : ConfigurationElement 
    { 
     [ConfigurationProperty("customsettingitem", IsRequired = false)] 
     public int CustomSettingItem { get { return (int)this["customsettingitem"]; } } 
    } 
} 

답변

4

2 개 개의 물건을 내 머리가 너무처럼 된 DefaultValue를 사용하는 것입니다 : 가정

[ConfigurationProperty("customsettingitem", DefaultValue = -1)] 
    public int CustomSettingItem { get { return (int)this["customsettingitem"]; } } 

유효하지 않은 몇 가지 가치가있다. 이 경우 CustomSettingItem == -1은 설정되지 않았 음을 의미하고> = 0은 config에 설정된 값이었습니다. 물론 -1은 유효하지 않은 입력을 가정합니다. 아무것도 설정에 설정되어 있지 않은 경우

[ConfigurationProperty("customsettingitem", IsRequired = false)] 
    public int? CustomSettingItem { get { return (int?)this["customsettingitem"]; } } 

자, 내가 수 없었습니다 지금까지 0 대신

+0

그게 효과가 있지만, 속성이 정의되지 않은 경우 기본값을 억제하는 방법이 있기를 바랬습니다. 현재 사용중인 작업은 config.Setting2.IsPresent – user62064

0

의 디폴트로 null한다 :

두 번째 아이디어는 대신 널 (NULL)의 INT를 사용하는 것입니다 구성 파일에 정의되지 않은 경우 속성이 null이되도록 알립니다. 그것은 그것의 무한한 지혜, Microsoft는 당신이 정말로 String.Empty 또는 새 ConfigurationElement() null을 입력하면 결정했다.

나는 현재 그것을 해결 해요 방법은 다음과 같이이다 :

bool _hasProp = true; 
    protected override object OnRequiredPropertyNotFound(string name) 
    { 
     if (name == "prop") 
     { 
      _hasProp = false; 
      return null; // note that this will still not make prop null 
     } 
     return base.OnRequiredPropertyNotFound(name); 
    } 

    [ConfigurationProperty("prop", IsRequired = true)] 
    public string Prop 
    { 
     get { return _hasProp ? (string) this["prop"] : null; } 
    } 

그것은 해킹 및 필요에 따라 속성을 표시 잘못됩니다. 구성 파일을 편집하기 위해 도구를 사용하고 있다면이 파일은 마음에 들지 않습니다.

11

가장 좋은 방법은 ConfigurationSection.PostDeserialize()을 무시하고 ConfigurationElement에서 파생 된 각 섹션 구성원의 IsPresent 속성을 확인하는 것입니다.

public class CustomSettingsHandler : ConfigurationSection 
{ 
    // ... 

    protected override void PostDeserialize() 
    { 
     foreach (ConfigurationProperty property in Properties) 
     { 
      var configElement = this[property] as ConfigurationElement; 

      if (configElement != null 
       && !configElement.ElementInformation.IsPresent) 
      { 
       this[property] = null; 
      } 
     } 

     base.PostDeserialize(); 
    } 
} 

이후 null 될 것 config 파일에서 읽지 않은 각 ConfigurationElement

.

+0

입니다. 참고로 'PostDeserialize' 이벤트에서이 작업을 수행 할 필요가 없습니다. 'ElementInformation'은 항상 사용 가능합니다 :'Console.WriteLine ("Setting1 {0}", config.Setting1.CustomSettingItem.ElementInformation.IsPresent? "Y": "N");' –

2

는 다음과 같은 시도 : 값에서 온 않는 경우

configElement.ElementInformation.Properties[propName].ValueOrigin = 
     PropertyValueOrigin.SetHere 

ValueOrigin 속성을 알려줍니다.

+0

'IsPresent'가 예상 한 값을 반환하지 않았습니다. 어떤 이유로 든 값 (모든 것에 대해 false를 반환 함).'ValueOrigin'이 나를 위해 일했습니다. – atheaos

0

또한 다음 사용하여 확인할 수 있습니다 : 그것은 당신의 config 파일에서 찾을 수 없습니다 경우

config.Setting1.CustomSettingItem.ElementInformation.IsPresent 

당신이 잘못된 줄 것이다.