這是我的方法:如何從詞典(鍵,值)在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中手動提供)。 所以我想要的是,當屬性的方式來驗證,如果該屬性被發現爲空或空白,那麼其相應的字段名,這實際上是字典的值將被添加到上面的方法中的字符串消息。
我希望我很清楚。
任何不使用System.ComponentModel.DataAnnotations類的理由? –
感謝您的建議。我會檢查出來.. –