通用约束——我不确定如何用非此即彼的情况来解决这种情况
基本上我有以下内容:
public static bool IsBetween<T>(this T value, T a, T b)
where T : IComparable
{
...
}
public static bool IsBetween<T>(this T value, T a, T b)
where T : IComparable<T>
{
...
}
问题是我不能这样做,因为即使约束不同,也不能拥有具有相同签名的成员。但是,无法声明约束是 IComparable
或 IComparable
。所以,我不知道除了选择一个并使用它之外还能做什么。而且,无论我选择哪一个,我都会失去另一个,因为它们是独立的并且不会相互继承(这是有道理的)。
我是否遗漏了一些东西,有没有一种方法可以同时使用两者,或者我是否必须选择一个(可能是通用版本)?
Basically I have the following:
public static bool IsBetween<T>(this T value, T a, T b)
where T : IComparable
{
...
}
public static bool IsBetween<T>(this T value, T a, T b)
where T : IComparable<T>
{
...
}
The problem is I can't do this because you can't have a member with the same signature, even if the constraints are different. But, there is no way to state that the constraint is either IComparable
OR IComparable<T>
. So, I'm not sure what to do here outside of just picking one and going with it. And, no matter which one I pick I'm losing out on the other because they are separate and don't inherit from each other (which makes sense).
Am I missing something here in that is there a way to accomplish using both, or am I going to have to pick one (probably the generic version)?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我根本不明白为什么第一种方法是通用的。为什么不只是:
使方法通用会增加什么价值?显然,您不会避免装箱惩罚,因为当您调用
CompareTo(object)
时,这些值将被装箱。除非您有令人信服的理由使该方法通用,否则不要使其通用。然后它具有与其他方法不同的签名,您的问题就解决了。
I don't understand why the first method is generic at all. Why isn't it just:
What value does making the method generic add? Obviously you're not going to avoid the boxing penalty because the values are going to be boxed when you call
CompareTo(object)
.Unless you have some compelling reason to make the method generic, don't make it generic. It then has a different signature from the other method, and your problem is solved.
在 .NET 方法解析重载中,不考虑返回类型和泛型约束。因此,即使
IComparable
和IComparable
有一些共同点,仍然无法正常工作。只需选择IComparable
版本即可。标准 .NET 类型(例如 Int32、Decimal、DateTime 等)无论如何都实现这两个接口。In .NET method resolution overload doesn't take into account return types and generic constraints. So even if
IComparable
andIComparable<T>
had something in common that would still not work. Just pick theIComparable<T>
version. Standard .NET types such as Int32, Decimal, DateTime, ... implement both interfaces anyway.