This commit is contained in:
Dan Clark
2024-11-28 21:52:42 +00:00
parent a457f4d6df
commit aeff13a105
5 changed files with 95 additions and 36 deletions
+36
View File
@@ -0,0 +1,36 @@
namespace Toolkit.Foundation;
public static class ResultExtensions
{
public static TResult Failure<TResult>(this object? sender,
Reason reason)
where TResult : Result
{
if (typeof(TResult).IsGenericType && typeof(TResult).GetGenericTypeDefinition() == typeof(Result<>))
{
object? value = sender is not null && typeof(TResult).GetGenericArguments()[0].IsAssignableFrom(sender.GetType())
? sender : Activator.CreateInstance(typeof(TResult).GetGenericArguments()[0].MakeNullable());
return (TResult)Activator.CreateInstance(typeof(TResult), value, false, reason)!;
}
return (TResult)Activator.CreateInstance(typeof(TResult), false, reason)!;
}
public static TResult Success<TResult>(this object? sender)
where TResult : Result
{
if (typeof(TResult).IsGenericType && typeof(TResult).GetGenericTypeDefinition() == typeof(Result<>))
{
object? value = sender is not null && typeof(TResult).GetGenericArguments()[0].IsAssignableFrom(sender.GetType())
? sender : Activator.CreateInstance(typeof(TResult).GetGenericArguments()[0].MakeNullable());
return (TResult)Activator.CreateInstance(typeof(TResult), value, true, Reason.None)!;
}
return (TResult)Activator.CreateInstance(typeof(TResult), true, Reason.None)!;
}
public static TResult Create<TResult>(this object? sender, bool condition)
where TResult : Result => condition ? sender.Success<TResult>() : sender.Failure<TResult>(Reason.ConditionNotMet);
}