Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/.net/22.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 是否可以在运行时检测当前未检查/检查的算术上下文?_C#_.net_Integer Arithmetic - Fatal编程技术网

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

C# 是否可以在运行时检测当前未检查/检查的算术上下文?,c#,.net,integer-arithmetic,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;

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

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;
    }
}

如果答案只是“不”,不要害怕简单地说:

所以答案似乎是“不”,但我找到了解决我特定问题的方法。它可能对最终陷入这种情况的其他人有用

public NarrowChar(Char c) {
    var b = (Byte)c;
    this.b = (c & 255) != c ? (Byte)'?' : b;
}
首先,我们通过尝试强制转换来探测选中/未选中的上下文。如果选中,溢出异常将由字节c引发。如果未选中,位掩码和与c的比较将告诉我们是否在强制转换中存在溢出。在我们的特殊情况下,我们需要窄带字符的语义,以便将不适合字节的字符设置为?;就像你把一串™ 到ISO-8759-1或ASCII,您得到了吗


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

这已经写满了它。你到底想解决什么问题?不管通过字符串值来回发送int.MaxValue有什么意义?为什么要有这个字段,为什么要这样初始化它?@PeterDuniho编译器显然不会让你溢出。我只是在示例中绕开它。@PeterDuniho我正在实现一个类型,我希望它与基本类型具有相同的语义,在本例中,它是一个更大的转换运算符type@PeterDuniho在提供建设性问题或答案之前,是否有一个假设“XY问题”的名称P@NickStrupat我认为这是一个公平的假设。为什么需要检查是否处于选中的{}块中?与原语相同的语义是,如果没有异常,只需抛出异常,如果将值转换为无法存储它的较小类型,则会发生异常。您能否提供一个您打算使用IsChecked的示例?