Created
June 29, 2018 00:57
-
-
Save badcommandorfilename/86f19bb5865da5f56b56ea778e1a7af8 to your computer and use it in GitHub Desktop.
C# Runtime type Cast and CastEnumerable
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
static IEnumerable CastEnumerable(IEnumerable<object> input, Type t) | |
{ | |
foreach(var o in input) | |
{ | |
yield return Cast(o, t); | |
} | |
} | |
static object Cast(object obj, Type t) | |
{ | |
try | |
{ | |
var param = Expression.Parameter(obj.GetType()); | |
return Expression.Lambda(Expression.Convert(param, t), param) | |
.Compile().DynamicInvoke(obj); | |
} | |
catch (TargetInvocationException ex) | |
{ | |
throw ex.InnerException; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment