情况如下:
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其中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());
}
答案 0 :(得分:7)
你不能施放它但你可以使用ToDictionary:
itemList.ToDictionary(s=>s.Name, s.Address);