【发布时间】:2013-01-23 03:21:51
【问题描述】:
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'会执行很多次,性能很差。我该如何解决这个问题。
【问题讨论】:
-
你能把Animal上的
NickName改成Name吗? -
如果你想要性能,使用带有属性
Name的Base接口并在Peploe和Animal实现它 -
@shf301 抱歉,我无法更改。