我如何检查一个数字是正的或负的c# ?


当前回答

public static bool IsNegative<T>(T value)
   where T : struct, IComparable<T>
{
    return value.CompareTo(default(T)) < 0;
}

其他回答

num < 0 // number is negative
    public static bool IsPositive<T>(T value)
        where T : struct, IComparable<T>
    {
        return value.CompareTo(default(T)) > 0;
    }
public static bool IsNegative<T>(T value)
   where T : struct, IComparable<T>
{
    return value.CompareTo(default(T)) < 0;
}

对于32位有符号整数,例如System。Int32,也就是c#中的int:

bool isNegative = (num & (1 << 31)) != 0;
bool positive = number > 0;
bool negative = number < 0;