我有以下switch语句-它接受我从Web服务获得的响应,并将它们映射到我的对象级别的字段,然后将更新持久化到DB。
foreach (var webServiceResponse in response.Values)
{
switch (webServiceResponse.Name)
{
case Constants.A:
myObject.A = (double) webServiceResponse.Value;
break;
case Constants.B:
myObject.B = (double) webServiceResponse.Value;
break;
case Constants.C:
myObject.C = (double) webServiceResponse.Value;
break;
//numerous more same pattern removed for readability
}
}有没有更好的模式可以用来摆脱switch语句,只需循环所有的响应,并将它们映射到我的对象上的字段?也许字典将是最好的方法-如果有人有代码样本或链接到与字典类似的事情?
发布于 2014-05-29 04:41:18
假设Constants.whatever确实与myObject上的属性名称相匹配,则可以使用反射来完成此操作。
foreach (var webServiceRespone in response.Values)
{
PropertyInfo propInfo = myObject.GetType().GetProperty(webServiceResponse.Name);
if (propInfo != null)
propInfo.SetValue(myObject, webServiceResponse.Value);
}发布于 2014-05-29 05:53:19
下面是我循环所有响应并使用字典和反射将它们映射到对象上的字段的方法。
以下是包含字段定义的字典
private static Dictionary<string, string> GetAttributeNames()
{
Dictionary<string, string> dic = new Dictionary<string, string>()
{
{ "Name1", "Name - 1" },
{ "Name2", "Name - 2" },
{ "Name3", "Name - 3" }
};
return dic;
}循环并将它们映射到对象的字段
foreach (KeyValuePair<String, String> row in GetAttributeNames())
{
myClass myobj = new myClass
{
FieldName = row.Value,
FieldValue = PropertyHasValue(response.Values, row.Key),
};
}和反射方法
// using reflection to get the object's property value
public static String PropertyHasValue(object obj, string propertyName)
{
try
{
if (obj != null)
{
PropertyInfo prop = obj.GetType().GetProperty(propertyName, BindingFlags.Instance | BindingFlags.Public);
if (prop != null)
{
string sVal = String.Empty;
object val = prop.GetValue(obj, null);
if (prop.PropertyType != typeof(System.DateTime?))
sVal = Convert.ToString(val);
else // format the date to contain only the date portion of it
sVal = Convert.ToDateTime(val).Date.ToString("d"); ;
if (sVal != null)
{
return sVal;
}
}
}
return null;
}
catch
{
return null;
}
}我相信你可以根据你的需要来定制它。
https://stackoverflow.com/questions/23921348
复制相似问题