【发布时间】:2016-07-18 03:12:38
【问题描述】:
--EDIT-- 重写以更好地阐明我想要做什么,以及问题是什么。抱歉,它不简洁,但上下文可能有助于理解。
我有一个程序,可以针对各种场景运行多个模拟。我将这些模拟和场景的结果存储在一个类(“结果类”)中,将基本结果存储为类的属性,并将各种场景和敏感性存储在类内的字典中。
因为不同的用户会希望从模拟中获得不同的输出,所以我正在尝试开发一种允许用户生成自定义报告的方法。为此,我使用反射。我使用反射来处理结果类中的每个属性,并将其添加到树视图中,使用与报告类相同的层次结构。然后,用户可以浏览树形视图,查看每个属性,并在报告中选择他们想要的属性。
当用户选择要报告的属性时,我使用树层次结构将其转换为“路径” - 一个分隔字符串,用于描述感兴趣项目的属性分支:例如:
Results.TotalCapacity; or:
Results.UsableCapacity; or
Results.Scenarios[HighCase].TotalCapacity; or
Results.Sensitivity.ModifiedCapacity.
最终,我想使用反射来解析这些路径,并从中检索值。
我从 this link 大量借用了代码,但是当路径中的对象之一是字典时,我正在努力寻找检索适当对象的最佳方法。
我已经设法让它发挥作用,但如果能提供任何关于如何改进或使其更强大的反馈,我将不胜感激。将字典转换为列表然后通过索引获取键显然不是最佳选择。我可以修改我的“路径”代码以返回字典键,但不确定如何使用反射从键中获取字典值。
代码如下:
public object GetPropertyValueFromPath(object baseObject, string path)
{
//Split into the base path elements
string[] pp = CorrectPathForDictionaries(path).Split(new[]{ '.' }, StringSplitOptions.RemoveEmptyEntries);
//Set initial value of the ValueObject
object valueObject = baseObject;
foreach (var prop in pp)
{
if (prop.Contains("["))
{
//Will be a dictionary. Get the name of the dictionary, and the index element of interest:
string dictionary = prop.Substring(0, prop.IndexOf("["));
int index = Convert.ToInt32(prop.Substring(prop.IndexOf("[") + 1, prop.Length - prop.IndexOf("]")));
//Get the property info for the dictionary
PropertyInfo dictInfo = valueObject.GetType().GetProperty(dictionary);
if (dictInfo != null)
{
//Get the dictionary from the PropertyInformation
valueObject = dictInfo.GetValue(valueObject, null);
//Convert it to a list to provide easy access to the item of interest. The List<> will be a set of key-value pairs.
List<object> values = ((IEnumerable)valueObject).Cast<object>().ToList();
//Use "GetValue" with the "value" parameter and the index to get the list object we want.
valueObject = values[index].GetType().GetProperty("Value").GetValue(values[index], null);
}
}
else
{
PropertyInfo propInfo = valueObject.GetType().GetProperty(prop);
if (propInfo != null)
{
valueObject = propInfo.GetValue(valueObject, null);
}
}
}
return valueObject;
}
【问题讨论】:
-
顺便说一句:“CorrectPathForDictionaries”只是获取路径并更正它,以便将 Scenario.[3].ModifiedCapacity 更改为 'Scenario[3].ModifiedCapacity.
-
你试过什么?请附上一个很好的minimal reproducible example,清楚地展示您尝试过的内容,并准确描述您遇到的具体问题。请注意,在编译时您不知道类型参数的字典上反射的相关成员(如果您知道,那么当然您可以将对象转换为正确的字典类型)是
Item属性。
标签: c# dictionary reflection