是否可以在运行时检测当前未检查/检查的算术上下文?

时间:2017-02-06 02:34:17

标签: c# .net integer-arithmetic

我可以用这样的东西来检查......

private static readonly int IntMaxValue = int.Parse(int.MaxValue.ToString());
private static bool IsChecked()
{
    try {
        var i = (IntMaxValue + 1);
        return false;
    }
    catch (OverflowException) {
        return true;
    }
}

...但是这是一个紧密循环中的大量开销,只是为了检测它而抛出和捕获。有更轻松的方法吗?

编辑更多背景信息......

struct NarrowChar
{
    private readonly Byte b;
    public static implicit operator NarrowChar(Char c) => new NarrowChar(c);
    public NarrowChar(Char c)
    {
        if (c > Byte.MaxValue)
            if (IsCheckedContext())
                throw new OverflowException();
            else
                b = 0; // since ideally I don't want to have a non-sensical value
        b = (Byte)c;
    }
}

如果答案是'不',不要害怕简单地说:)

1 个答案:

答案 0 :(得分:1)

所以答案似乎是'不',但我找到了解决我特定问题的方法。对于最终处于这种情况的其他人来说,这可能是有用的。

public NarrowChar(Char c) {
    var b = (Byte)c;
    this.b = (c & 255) != c ? (Byte)'?' : b;
}

首先,我们通过尝试强制转换来“探测”已检查/未检查的上下文。如果我们选中了,(Byte) c会抛出溢出异常。如果我们未选中,则位掩码和与c的比较会告诉我们是否存在溢出。在我们的特定情况下,我们需要NarrowChar的语义,以使Char中不适合的Byte设置为?;就像将String 转码为ISO-8759-1或ASCII转换为?一样。

首先执行强制转换对语义很重要。内联b将打破“探测”行为。