如何确定通用数字参数是否未签名?

the*_*aob 3 c# generics random

我有一个通用的方法来生成最小和最大的随机数.我也有类似的函数来生成具有相同限制的越界值.

但问题是,我需要填写不同类型的变量.有些变量是无符号的,最小 - 最大范围与它们的无符号类型相同.

当我尝试为这些变量创建越界值时,我超出了变量的限制(确切地说是ushort).

这是我的通用方法:

    private static U GenerateOutOfBounds<U>(U minimum, U maximum) where U : IComparable, IFormattable, IConvertible
    {
        bool b       = g.NextBoolean();
        long signCheckForMinimum = Convert.ToInt64(minimum);
        double maxpp = g.NextDouble(Convert.ToDouble(maximum), Convert.ToDouble(maximum) + g.Next());
        double minpp = g.NextDouble(Convert.ToDouble(maximum), Convert.ToDouble(maximum) + g.Next());
        if (signCheckForMinimum >= 0)
        {
            b = true;
        }

        if (b)
        {
            return (U)Convert.ChangeType(maxpp, Type.GetTypeCode(typeof(U)));
        }
        else
        {
            return (U)Convert.ChangeType(minpp, Type.GetTypeCode(typeof(U)));
        }
    }
Run Code Online (Sandbox Code Playgroud)

我试图确定这个数字是否是无符号的,并将其转换为很长时间,但我现在可以看到这种方法非常错误.

那么如何确定我得到的变量是无符号的还是有没有办法检查该类型是否是无符号的而不与所有无符号类型进行比较?

小智 9

bool signed = Convert.ToBoolean(typeof(U).GetField("MinValue").GetValue(null));
Run Code Online (Sandbox Code Playgroud)

带符号的类型具有非零MinValue常量,它将true在布尔强制转换期间转换为.