您不能在逻辑上使Type type
参数与< T >
通用参数匹配。
扩展方法必须返回非泛型IEnumerable
。
有可能使这个语法IEnumerable
实际上(在运行时)拥有一个泛型IEnumerable < That particular type >
,但执行您的扩展方法的用户程序员必须做出假设、检查和强制转换。
InvalidCastException
请注意,如果您走这条路并且用户程序员不知道这些事情,您可能最终会遇到:)。
它是这样的:
public static class SomeExtensions {
private static readonly MethodInfo methodDefOf_PrivateHelper = typeof(SomeExtensions)
.GetMethod("PrivateHelper",
BindingFlags.NonPublic | BindingFlags.Static,
Type.DefaultBinder,
new [] { typeof(System.Collections.IEnumerable) },
null);
private static IEnumerable<T> PrivateHelper<T>(System.Collections.IEnumerable @this){
foreach (var @object in @this)
yield return (T)@object; // right here is were you can get the cast exception
}
public static System.Collections.IEnumerable DynamicCast(
this System.Collections.IEnumerable @this,
Type elementType
) {
MethodInfo particularizedMethod = SomeExtensions.methodDefOf_PrivateHelper
.MakeGenericMethod(elementType);
object result = particularizedMethod.Invoke(null, new object[] { @this });
return result as System.Collections.IEnumerable;
}
}
以下是你如何使用它:
object[] someObjects = new object[] { "one", "two", "three" };
IEnumerable implicitlyCastedToEnumerable = someObjects;
Type unknownType = (DateTime.Now.Hour > 14) ? typeof(string) : typeof(int);
IEnumerable apparentlyNothingHappenedHere
= implicitlyCastedToEnumerable.DynamicCast(unknownType);
// if it's not after 14:00, then an exception would've jumped over this line and
// straight out the exit bracket or into some catch clause
// it it's after 14:00, then the apparentlyNothingHappenedHere enumerable can do this:
IEnumerable<string> asStrings = (IEnumerable<string>)apparentlyNothingHappenedHere;
// whereas the earlier would've cause a cast exception at runtime
IEnumerable<string> notGoingToHappen = (IEnumerable<string>)implicitlyCastedToEnumerable;