假设我有以下内容:
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的所有具有类似列表的属性中循环。我有办法做到这一点吗?
正如我在评论中所建议的,使用协变接口可以实现这一点。
协方差/反方差:http://msdn.microsoft.com/en-us/library/ee207183.aspx
另请参阅:协方差和IList
工作样品
namespace Covariance
{
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
{
}
class Program
{
static void Main( string[] args ) {
MyContainer mc = new MyContainer();
mc.MyCircles.Add( new Circle { Area = 60 } );
Collect( mc );
Console.ReadLine();
}
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 IEnumerable<Shape>;
if( t != null ) {
foreach( Shape shape in t ) {
Console.WriteLine( shape.Area );
}
}
}
}
}
}
}
如果您将GetValue
行更改为以下行,它将起作用:
var t = property.GetValue(container, null) as IEnumerable<Shape>;
我用以下代码测试了它:
var c = new MyContainer();
c.MySquares.Add(new Square() { Area = 5, });
c.MySquares.Add(new Square() { Area = 7, });
c.MySquares.Add(new Square() { Area = 11, });
c.MyCircles.Add(new Circle() { Area = 1, });
c.MyCircles.Add(new Circle() { Area = 2, });
c.MyCircles.Add(new Circle() { Area = 3, });
Collect(c);
得到了以下结果:
5
7
11
1
2
3