说我有以下内容:
public class MyContainer
{
public string ContainerName { get; set; }
public IList<Square> MySquares { get; set; }
public IList<Circle> MyCircles { get; set; }
public MyContainer()
{
MySquares = new List<Square>();
MyCircles = new List<Circle>();
}
}
public class Shape
{
public int Area { get; set; }
}
public class Square : Shape
{
}
public class Circle : Shape
{
}
现在我有一个这样的功能:
private static void Collect(MyContainer container)
{
var properties = container.GetType().GetProperties();
foreach (var property in properties)
{
if (property.PropertyType.IsGenericType &&
property.PropertyType.GetGenericTypeDefinition() == typeof(IList<>) &&
typeof(Shape).IsAssignableFrom(property.PropertyType.GetGenericArguments()[0]))
{
var t = property.GetValue(container, null) as List<Square>;
if (t != null)
{
foreach (Shape shape in t)
{
Console.WriteLine(shape.Area);
}
}
}
}
当我到达该MySquares
物业时,这按我想要的方式工作,但是我希望改用以下方式:
var t = property.GetValue(container, null) as List<Shape>;
我希望它会循环遍历具有类似列表的所有 MyContainer 属性。我有什么办法可以做到这一点?