我需要一种方法来使用反射从泛型HashSet中获取值。这是我尝试过的(您可以在控制台应用上复制/粘贴):
class Program
{
public class Order
{
public int Id { get; set; }
}
public class Person
{
public string Name { get; set; }
public ICollection<Order> Orders { get; set; }
}
static void Main(string[] args)
{
var person = new Person();
person.Name = "Test Person";
person.Orders = new HashSet<Order>();
person.Orders.Add(new Order() { Id = 1 });
person.Orders.Add(new Order() { Id = 2 });
var reflectedOrders = person.GetType().GetProperty("Orders").GetValue(person, null);
Console.WriteLine("How do I iterate the reflected orders?");
Console.ReadLine();
}
}
这是一个例子,在实际应用程序中我不知道转换反射订单的类型。我只知道该属性是ICollection<T>
(由EF转为HashShet)
答案 0 :(得分:1)
您是否尝试将reflectedOrders
投射到IEnumerable
?
IEnumerable reflectedOrders = (IEnumerable)person.GetType().GetProperty("Orders").GetValue(person, null);
答案 1 :(得分:0)
铸造应该很简单:
var reflectedOrders = (HashSet<Order>) person.GetType().GetProperty("Orders").GetValue(person, null);
foreach (var order in reflectedOrders)
...
答案 2 :(得分:0)
怎么样?
var orders = persons.OfType<Person>().SelectMany(p => p.Orders);