C#泛函函数实现isPowerOf2 <T>(T x)

pho*_*ger 1 c# generics

在C++中,我经常使用这个模板化函数......

template<typename T>
bool isPowerOf2 (T x) // returns nonzero if x is a power-of-2
{
  return x && ((x & (~x + 1)) == x);
}
Run Code Online (Sandbox Code Playgroud)

...而且我正在尝试在C#中实现相同的功能.所以这是我能想到的最好的:

public class Utils
{
   // ...

   public static bool isPowerOf2<T>(T x) // returns true if x is a power-of-2
   {
      return (x != 0) && ((x & (~x + 1)) == x);
   }
}
Run Code Online (Sandbox Code Playgroud)

但Visual Studio抱怨error CS0019: Operator '!=' cannot be applied to operands of type 'T' and 'int'error CS0023: Operator '~' cannot be applied to operand of type 'T'.

如果我删除通用的东西,只是使它" public static bool isPowerOf2(int x)",它工作正常(就像在这里的各种实现),但我希望实现是通用的,所以它适用于任何整数类型.

das*_*ght 5

这很好地说明了为什么C#泛型不是C++模板.C#必须能够在不知道的情况下编译代码T,而C++可以推迟编译直到T知道类型.这让c + +弄清楚如何执行~,+,&,等等.

使用C#的最简单方法是为计划与函数一起使用的类型进行多次重载.这导致少量代码重复,但它比其他选项读取更好,例如使用LINQ表达式动态生成代码.

如果性能不重要,您还可以使用Convert.ToInt64:

bool isPowerOf2 (object obj) {
    var x = Convert.ToInt64(obj);
    return x && ((x & (~x + 1)) == x);
}
Run Code Online (Sandbox Code Playgroud)