Created
February 19, 2020 11:28
-
-
Save Mrnikbobjeff/9f5ec4110f64aa7d02fbefcaaacc2285 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
internal class NoReturn<TReturn, TException> where TException : Exception | |
{ | |
static NoReturn() | |
{ | |
bool GetCorrectConstructor(ParameterInfo[] parameters) => parameters.Length == 1 && parameters[0].ParameterType == typeof(string); | |
var constructors = typeof(TException).GetConstructors(); | |
var target = Expression.Label(); | |
var constructor = constructors.Single(c => GetCorrectConstructor(c.GetParameters())); | |
var messageExpression = Expression.Parameter(typeof(string), "message"); | |
var newException = Expression.New(constructor, messageExpression); | |
var throwExpression = Expression.Throw(newException, typeof(TReturn)); | |
var retExp = Expression.Return(target, Expression.Default(typeof(TReturn))); | |
var block = Expression.Block(throwExpression, retExp); | |
ThrowDelegate = Expression.Lambda<Func<string, TReturn>>(throwExpression, messageExpression).Compile(); | |
} | |
static Func<string, TReturn> ThrowDelegate; | |
internal TReturn Throw(string message) | |
{ | |
return ThrowDelegate(message); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment