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.
}
}
}
If I use reflection,it can resolve this problem. But when ‘ItemSource’ is very huge, the ‘foreach’ will excute many times,the performance is bad.How can I resolve this problem.
You need to add little bit of reflection to make is complete dynamic. And trust me that will not hurt performance as I am already using it. Here is code sample I have created from you sample. It is still not production ready but you will get the basic idea how you can do it, with all your restriction.
This code works exactly way you want. Its not depended on whatever property you have in class. Please let me know if any further details needed.