给一个基类Base
,我想写一个方法Test,像这样:
private static bool Test(IEnumerable enumerable)
{
...
}
如果 o 的类型实现了任何接口,则 Test 返回 trueIEnumerable<X>
where X
源自于Base
,所以如果我这样做:
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());
}
...但将其视为一个思想实验。
您还可以使用LINQ查询可能看起来像这样。
public static bool ImplementsBaseType(IEnumerable objects)
{
int found = ( from i in objects.GetType().GetInterfaces()
where i.IsGenericType &&
i.GetGenericTypeDefinition() == typeof(IEnumerable<>) &&
typeof(MyBaseClass).IsAssignableFrom(i.GetGenericArguments()[0])
select i ).Count();
return (found > 0);
}
此代码假定以下 using 语句:
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
因为这只是一个思想实验。这是作为扩展方法的另一种实现。
public static class ConversionAssistants
{
public static bool GenericImplementsType(this IEnumerable objects, Type baseType)
{
foreach (Type type in objects.GetType().GetInterfaces())
{
if (type.IsGenericType)
{
if (type.GetGenericTypeDefinition() == typeof(IEnumerable<>))
{
if (baseType.IsAssignableFrom(type.GetGenericArguments()[0]))
return true;
}
}
}
return false;
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)