在 C# 中,不可能有一个适用于 int 和 uint 的泛型方法,因为泛型类型必须是一个类而不是原始类型,或者这只是在约束条件下吗?
public decimal shift<T>(T input, byte b) where T : int, uint
{
///....
}
有什么方法可以不受限制地进行这项工作吗?
public decimal shift<T>(T input, byte b)
{
///....
}
当我执行后者时,我得到了进一步的结果,但在对 int 或 uint 进行移位操作时仍然出错。就好像,它在运行时不知道它是什么类型。
在 C# 中,为 native 类型编写特殊情况通常是通过方法重载完成的。在 BCL 中有几个地方可以看到这种设计,一个例子是 BitConverter
类。
如果您想要一个具有一些特殊情况的泛型版本,您可以添加一个泛型重载,C# 的类型推断将使其对最终用户透明。
public decimal shift(int input, byte b)
{
//....
}
public decimal shift(uint input, byte b)
{
//....
}
public decimal shift<T>(T input, byte b)
{
//....
}
用法:
shift(5, 1); //resolves to the 'int'overload
shift(5u, 1); //resolves to the 'uint' overload
shift(new Point(2, 2), 1) //resolves to the generic overload with T = Point
我猜您正在尝试使用通用方法进行位移。只有少数几种类型(byte、sbyte、short、ushort、int、uint、long、ulong)是有意义的,因此您最好只写出 8 个重载。我在我的一个项目中有一门课,其中包含很多位黑客,我只是写出了必要的重载,而且效果很好。