2011-09-24 87 views
0

這是我的方法:如何從詞典(鍵,值)在C#中檢索特定值

/// <summary> 
/// Uses Dictionary(Key,Value) where key is the property and value is the field name. 
/// Matches the dictionary of mandatory fields with object properties 
/// and checks whether the current object has values in it or 
/// not. 
/// </summary> 
/// <param name="mandatoryFields">List of string - properties</param> 
/// <param name="o">object of the current class</  
/// <param name="message">holds the message for end user to display</param> 
/// <returns>The name of the property</returns> 
public static bool CheckMandatoryFields(Dictionary<string,string > mandatoryFields, object o,out StringBuilder message) 
{ 
    message = new StringBuilder(); 
    if(mandatoryFields !=null && mandatoryFields.Count>0) 
    { 
     var sourceType = o.GetType(); 
     var properties = sourceType.GetProperties(BindingFlags.Public | BindingFlags.Static); 
     for (var i = 0; i < properties.Length; i++) 
     { 
      if (mandatoryFields.Keys.Contains(properties[i].Name)) 
      { 
       if (string.IsNullOrEmpty(properties[i].GetValue(o, null).ToString())) 
       { 
        message.AppendLine(string.Format("{0} name is blank.", mandatoryFields.Values)); 
       } 
      } 
     } 
     if(message.ToString().Trim().Length>0) 
     { 
      return false; 
     } 
    } 
    return true; 
} 

在此我有PARAMS字典將舉行類的屬性名稱和它對應的字段名UI(由開發人員在業務層或UI中手動提供)。 所以我想要的是,當屬性的方式來驗證,如果該屬性被發現爲空或空白,那麼其相應的字段名,這實際上是字典的值將被添加到上面的方法中的字符串消息。

我希望我很清楚。

+1

任何不使用System.ComponentModel.DataAnnotations類的理由? –

+0

感謝您的建議。我會檢查出來.. –

回答

1

執行循環的其他方式:

public static bool CheckMandatoryFields(Dictionary<string,string > mandatoryFields, object o,out StringBuilder message) 
{ 
    message = new StringBuilder(); 
    if(mandatoryFields == null || mandatoryFields.Count == 0) 
    { 
     return true; 
    } 

    var sourceType = o.GetType(); 
    foreach (var mandatoryField in mandatoryFields) { 
     var property = sourceType.GetProperty(mandatoryField.Key, BindingFlags.Public | BindingFlags.Static); 
     if (property == null) { 
      continue; 
     } 

     if (string.IsNullOrEmpty(property.GetValue(o, null).ToString())) 
     { 
      message.AppendLine(string.Format("{0} name is blank.", mandatoryField.Value)); 
     } 
    } 

    return message.ToString().Trim().Length == 0; 
} 

這樣你遍歷要檢查的屬性,所以你總是有「當前」屬性手柄和了解相應的鍵和價值詞典。

的片段

if (property == null) { 
    continue; 
} 

導致治療存在在詞典中的名稱,但不是對實際類型的屬性將被視爲有效屬性,以反映您的原始代碼做什麼功能。

+0

謝謝,我正在調查它... –

+0

需要幫助在這個http://stackoverflow.com/questions/7542793/how-to-get-the-type-of-a-property - 使用開關的病例中-C –