我经常遇到这个问题:我喜欢为不同的返回类型重载具有相同参数的某些方法,但.NET拒绝对密封的类/基元进行泛型约束。我将这种模式称为phantom generics
。
where
语句后面。 这是我的代码:
public static class Reinterpret {
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static unsafe float Cast<T>(int value) where T : float { //'float' is not a valid constraint. A type used as a constraint must be an interface, a non-sealed class or a type parameter.
return *((float*)&value); //reinterpret the bytes of 'value' to a float
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static unsafe float Cast<T>(uint value) where T : float { //'float' is not a valid constraint. A type used as a constraint must be an interface, a non-sealed class or a type parameter.
return *((float*)&value);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static unsafe double Cast<T>(long value) where T : double { //'double' is not a valid constraint. A type used as a constraint must be an interface, a non-sealed class or a type parameter.
return *((double*)&value);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static unsafe double Cast<T>(ulong value) where T : double { //'double' is not a valid constraint. A type used as a constraint must be an interface, a non-sealed class or a type parameter.
return *((double*)&value);
}
}
泛型不是模板。它们的行为不像模板。它们不能像模板一样工作。
“ phantom”泛型参数不会帮助您模拟模板(reinterpret_cast
无论如何,它也不是实际的模板),因为您很快就会遇到泛型不支持专业化的事实。
特别是,您问“有没有办法在泛型中使用显式类型来...使方法保持不同?” 并评论说“通用约束……使方法截然不同”。但是他们实际上没有。这些方法的区别仅在于参数类型不同。泛型是根据重载计算的,它们不会影响重载。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句