[英]How to retrieve the specific value from Dictionary(key,value) in 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中手動提供)。 所以我想要的是,當該屬性即將通過驗證時,如果發現該屬性為null或空白,則其相應的字段名(實際上就是字典的值)將被添加到上述方法中的stringbuilder消息中。
我希望我很清楚。
用另一種方式做循環:
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;
}
這樣,您就可以遍歷要檢查的屬性,因此始終可以對“ current”屬性進行處理,並從字典中了解相應的鍵和值。
片段
if (property == null) {
continue;
}
使函數將存在於字典中作為名稱存在但不視為類型上的實際屬性的屬性視為有效,以反映原始代碼的作用。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.