用于处理不返回的非 void 方法的 C# 选项

问题描述

我在我的一些代码中实现了 this answer,如:

private interface IMath<T> {
    internal T Add (T value1,T value2);
    internal T Negate (T value);
}

private class Math<T> : IMath<T> {
    internal static readonly IMath<T> P = Math.P as IMath<T> ?? new Math<T>();
    // !!! My question concerns this portion of code:
    T IMath<T>.Add (T a,T b) { NoSupport(); }
    T IMath<T>.Negate (T a) { NoSupport(); }
    private static void NoSupport () =>
        throw new NotSupportedException($"no math ops for {typeof(T).Name}");
    // !!! End code-of-interest.
}

private class Math : IMath<int>,IMath<float> {
    internal static Math P = new Math();
    int IMath<int>.Add (int a,int b) { return a + b; }
    int IMath<int>.Negate (int value) { return -value; }
    float IMath<float>.Add (float a,float b) { return a + b; }
    float IMath<float>.Negate (float value) { return -value; }
}

意图所在的位置,例如:

static T Negate <T> (T v) => Math<T>.P.Negate(v);

// elsewhere...
_ = Negate(3);    // ok (int)
_ = Negate(3.0f); // ok (float) 
_ = Negate(3.0);  // throws NotSupportedException (double)

那个 NoSupport() 函数是我遇到的问题。我只是添加它来处理针对不受支持的类型抛出异常和消息的问题,以便在添加更多操作时尽量保持代码简单。

但是,它无法编译 (C# 8),并在调用它的两个方法AddNegate)中出现预期的“并非所有控制路径都返回值”错误

我明白这一点,我明白为什么它不能编译,这是有道理的。但是,那么,我怎样才能实现既保持代码简单方便又让编译器满意的目标呢?

从我迄今为止所做的研究来看,似乎没有一种方法可以明确指定一个方法不会返回,但我想知道是否有办法...

  • ... 指定 NoSupport() 总是抛出异常?或者……
  • ... 将一行代码标记为无法访问(例如在调用 NoSupport() 之后)?或者……
  • ...将方法标记为始终实际返回值(覆盖编译器的分析)?

我的主要目标是消除冗余代码(即我对其他方法持开放态度),我的次要目标是了解 C# 的特定选项,用于处理所有路径 do 返回值的方法即使编译器看不到它(有什么选择吗?)。

我有这样一种感觉,即有一种非常直接的方法,而且我现在只见树木不见森林。

解决方法

最简单的解决方案是将 .eslintrc 从 void 更改为 rules: { 'indent': [2,2,{ 'SwitchCase': 1,'offsetTernaryExpressions': true }] }

于是变成:

NoSupport()

此外,您还可以使用 T 为您的错误消息增添一点趣味。这将自动包含调用 T IMath<T>.Add (T a,T b) => NoSupport(); T IMath<T>.Negate (T a) => NoSupport(); private static T NoSupport () => throw new NotSupportedException($"no math ops for {typeof(T).Name}"); 的方法的名称。

CallerMemberNameAttribute