【发布时间】:2017-02-03 15:53:24
【问题描述】:
情况如下:
public class Foo
{
public string Name {get;set;}
public List<Bar> barITems{get; set;}
}
public class Bar
{
public string Name{get; set;}
public string Address{get; set;}
}
我需要创建 Dictionary where key - Bar 类属性名称和值 - Bar 类相关值。这是我所做的尝试:
Type a = typeof(Foo);
PropertyInfo[] properties = a.GetProperties();
foreach (var property in properties)
{
if(property.Name == "barItems")
{
var barProperty = property.GetValue(Foo);
var itemList= barProperty as IEnumerable;
var barDictionary = new Dictionary<string,string>();
barDictionary = itemList; //how to cast it ?
continue;
}
fooDictionary.Add(property.Name, property.GetValue(Foo).ToString());
}
【问题讨论】:
-
您尝试过的方法有什么问题?
-
@Servy 无法从 IEnumerable 将其转换为字典
-
你的字典应该是 Dictionary
> -
这是有道理的。 itemList 的类型为 IEnumerable,您尝试将其分配给不接受 List
的 Dictionary。当您可以滚动列表并以这种方式为字典分配键值对时,为什么还要使用反射? -
我试图测试你的代码,但它在这一行有一个错误: var barProperty = property.GetValue(Foo); Foo 是一种类型,但您用作变量。
标签: c# .net linq dictionary casting