看来 OP 的意图是找到一个好的模式来解决他的问题并解决他当时正在努力解决的当前问题。
OP:“我可以将每个计算包装在一个辅助方法中,该方法在失败时返回 null,
然后只使用?? 运算符,但有没有更普遍的方法
(即不必为我想使用的每种方法编写辅助方法)?
我考虑过使用包含任何给定的泛型的静态方法
try/catch 中的方法并在失败时返回 null,
但我不确定我会怎么做。有什么想法吗?”
我看到了很多很好的避免嵌套 try catch 块的模式,张贴在此提要中,但没有找到解决上述问题的方法.
所以,这里是解决方案:
正如上面提到的 OP,他想制作一个包装器对象在失败时返回 null。
我将其称为 pod(异常安全的 pod)。
public static void Run()
{
// The general case
// var safePod1 = SafePod.CreateForValueTypeResult(() => CalcX(5, "abc", obj));
// var safePod2 = SafePod.CreateForValueTypeResult(() => CalcY("abc", obj));
// var safePod3 = SafePod.CreateForValueTypeResult(() => CalcZ());
// If you have parameterless functions/methods, you could simplify it to:
var safePod1 = SafePod.CreateForValueTypeResult(Calc1);
var safePod2 = SafePod.CreateForValueTypeResult(Calc2);
var safePod3 = SafePod.CreateForValueTypeResult(Calc3);
var w = safePod1() ??
safePod2() ??
safePod3() ??
throw new NoCalcsWorkedException(); // I've tested it on C# 7.2
Console.Out.WriteLine($"result = {w}"); // w = 2.000001
}
private static double Calc1() => throw new Exception("Intentionally thrown exception");
private static double Calc2() => 2.000001;
private static double Calc3() => 3.000001;
但是,如果您想为 CalcN() 函数/方法返回的 Reference Type 结果 创建一个安全 pod,该怎么办。
public static void Run()
{
var safePod1 = SafePod.CreateForReferenceTypeResult(Calc1);
var safePod2 = SafePod.CreateForReferenceTypeResult(Calc2);
var safePod3 = SafePod.CreateForReferenceTypeResult(Calc3);
User w = safePod1() ?? safePod2() ?? safePod3();
if (w == null) throw new NoCalcsWorkedException();
Console.Out.WriteLine($"The user object is {{{w}}}"); // The user object is {Name: Mike}
}
private static User Calc1() => throw new Exception("Intentionally thrown exception");
private static User Calc2() => new User { Name = "Mike" };
private static User Calc3() => new User { Name = "Alex" };
class User
{
public string Name { get; set; }
public override string ToString() => $"{nameof(Name)}: {Name}";
}
因此,您可能会注意到没有必要“为您要使用的每个方法编写辅助方法”。
两种类型的 pod(ValueTypeResults 和 ReferenceTypeResults)足够。
这里是SafePod的代码。虽然它不是一个容器。相反,它为ValueTypeResults 和ReferenceTypeResults 创建了一个异常安全的委托包装器。
public static class SafePod
{
public static Func<TResult?> CreateForValueTypeResult<TResult>(Func<TResult> jobUnit) where TResult : struct
{
Func<TResult?> wrapperFunc = () =>
{
try { return jobUnit.Invoke(); } catch { return null; }
};
return wrapperFunc;
}
public static Func<TResult> CreateForReferenceTypeResult<TResult>(Func<TResult> jobUnit) where TResult : class
{
Func<TResult> wrapperFunc = () =>
{
try { return jobUnit.Invoke(); } catch { return null; }
};
return wrapperFunc;
}
}
这就是您可以利用空合并运算符 ?? 与 一等公民 实体 (delegates) 的力量相结合的方式。