Created
October 26, 2016 19:47
-
-
Save caleblloyd/1659b365fc86acd774ce7034400b05ce to your computer and use it in GitHub Desktop.
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
public override T GetFieldValue<T>(int ordinal) | |
{ | |
try | |
{ | |
return base.GetFieldValue<T>(ordinal); | |
} | |
catch (InvalidCastException e) | |
{ | |
return ConvertWithReflection<T>(ordinal, e); | |
} | |
} | |
public override async Task<T> GetFieldValueAsync<T>(int ordinal, CancellationToken cancellationToken) | |
{ | |
try | |
{ | |
return await base.GetFieldValueAsync<T>(ordinal, cancellationToken).ConfigureAwait(false); | |
} | |
catch (InvalidCastException e) | |
{ | |
return ConvertWithReflection<T>(ordinal, e); | |
} | |
} | |
private T ConvertWithReflection<T>(int ordinal, InvalidCastException e) | |
{ | |
try | |
{ | |
// try casting using reflection | |
var dataParam = Expression.Parameter(typeof(string), "data"); | |
var body = Expression.Block(Expression.Convert(dataParam, typeof(T))); | |
var run = Expression.Lambda(body, dataParam).Compile(); | |
return (T) run.DynamicInvoke(GetReader().GetValue(ordinal)); | |
} | |
catch (Exception) | |
{ | |
// throw original InvalidCastException | |
throw e; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment