public class Peploe
{
public string Name { get; set; }
}
public class Animal
{
public string NickName { get; set; }
}
internal static class Program
{
/// <summary>
/// This 'ItemSorce' will be assignment by anywhere , so i don't know it have 'Name' property.
/// </summary>
public static IEnumerable ItemSource { get; set; }
private static void Main()
{
var list = new List<Peploe>() {new Peploe() {Name = "Pato"}};
ItemSource = list;
//Test2
//var animals = new List<Animal>() { new Animal() { NickName = "Pi" } };
//ItemSource = animals;
dynamic dy;
foreach (var item in ItemSource)
{
dy = item;
Console.WriteLine(dy.Name);//If I Uncomment 'Test2',it will throw a RuntimeBinderException at here.
}
}
}
如果我使用反射,它可以解决这个问题。但是当'ItemSource'非常大时,'foreach'会执行很多次,性能很差。我该如何解决这个问题。