【发布时间】:2010-03-30 18:02:04
【问题描述】:
给一个基类Base,我想写一个方法Test,像这样:
private static bool Test(IEnumerable enumerable)
{
...
}
如果 o 的类型实现 IEnumerable<X> 的任何接口,其中 X 派生自 Base,则 Test 返回 true,这样如果我会这样做:
public static IEnumerable<string> Convert(IEnumerable enumerable)
{
if (Test(enumerable))
{
return enumerable.Cast<Base>().Select(b => b.SomePropertyThatIsString);
}
return enumerable.Cast<object>().Select(o => o.ToString());
}
...它会做正确的事,使用反射。我确信这是遍历该类型的所有接口以找到符合要求的第一个接口的问题,但我很难在其中找到通用的IEnumerable<>。
当然,我可以考虑这个:
public static IEnumerable<string> Convert(IEnumerable enumerable)
{
return enumerable.Cast<object>().Select(o => o is Base ? ((Base)o).SomePropertyThatIsString : o.ToString());
}
...但可以将其视为思想实验。
【问题讨论】:
-
你的代码sn-ps没有意义,“o”从何而来?
-
也许你应该阅读 lambda 表达式。
标签: c# linq reflection