在C++中我經常使用這個模板函數...C#泛型函數isPowerOf2 <T>(T X)的實施
template<typename T>
bool isPowerOf2 (T x) // returns nonzero if x is a power-of-2
{
return x && ((x & (~x + 1)) == x);
}
...,我想要實現在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);
}
}
但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)
」,它工作正常(就像在various implementations here),但我想的實施是通用的,所以它會在任何整數類型的工作。
我不是一個C#專家,但我認爲答案是否定的,你不能這樣做。 http://stackoverflow.com/q/32664/3973077 –
「任何整數類型」你是指任何數字,如雙或十進制?您必須將'T'限制爲僅數字(而不是字符串),但我認爲這不能在C#中完成。 –