另一种方法是使用System.Reflection
. 尝试这个:
foreach (var r in results)
{
string name, trimmedName = "";
if (r.GetType() == typeof(ExpandoObject))
{
name = ((IDictionary<string,object>)r).ToList()
.Aggregate<KeyValuePair<string,object>, string>("", (s, p) =>
{
return s + " " + p.Value;
});
trimmedName = name.Trim();
}
else
{
PropertyInfo[] ps = r.GetType().GetProperties();
name = ps.Aggregate<PropertyInfo, string>("", (s, p) =>
{
return s + " " + p.GetValue(r);
});
trimmedName = name.Trim();
}
// use the trimmedName
Console.WriteLine(trimmedName);
}
[编辑] 基于@pwas 的建议,这是他的代码版本,具有改进的循环复杂性:
foreach (var r in results)
{
ProcessResult(r);
}
其中ProcessResult
有 2 个重载:
static void ProcessResult(ExpandoObject r)
{
string name, trimmedName = "";
name = ((IDictionary<string, object>)r).ToList()
.Aggregate<KeyValuePair<string, object>, string>("", (s, p) =>
{
return s + " " + p.Value;
});
trimmedName = name.Trim();
FurtherProcess(trimmedName);
}
static void ProcessResult(object r)
{
string name, trimmedName = "";
PropertyInfo[] ps = r.GetType().GetProperties();
name = ps.Aggregate<PropertyInfo, string>("", (s, p) =>
{
return s + " " + p.GetValue(r);
});
FurtherProcess(trimmedName);
}
private static void FurtherProcess(string trimmedName)
{
Console.WriteLine(trimmedName);
}
这是改进:
Type Maintainability Cyclomatic
Index Complexity
Program 54 24
// After code optimization
Program 69 16