如何确定值是否为零?

SWe*_*eko 2 c#

我有一个值为盒装(任意)数字类型或可以为空的数字类型.我需要检查该值是否为零.

基本上我有这个:

public bool IsZero(object value)
{
   if (value == null)
            return false;

   //lifted from the mvc sources, so I guess it's exhaustive
   HashSet<Type> numericTypes = new HashSet<Type>(new Type[] {
        typeof(byte), typeof(sbyte),
        typeof(short), typeof(ushort),
        typeof(int), typeof(uint),
        typeof(long), typeof(ulong),
        typeof(float), typeof(double), 
        typeof(decimal)
    });

   Type type = Nullable.GetUnderlyingType(value.GetType()) ?? value.GetType();

   if (!numericTypes.Contains(type))
      return false;

   // how do I get the value here ?
}
Run Code Online (Sandbox Code Playgroud)

我没有看到一种简单的方法来比较int值和int零,以及一个字节值为0的字节值.

我看到的一个解决方法是将正确键入的零值与每种类型相关联并检查,但是如果我最终需要一个"IsOne"方法,我想重用该解决方案.

Sha*_*ard 8

这有什么问题?

return value != null && value.ToString().Equals("0");
Run Code Online (Sandbox Code Playgroud)