通用约束——我不确定如何用非此即彼的情况来解决这种情况

发布于 2025-01-06 20:28:19 字数 494 浏览 2 评论 0原文

基本上我有以下内容:

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>
{
    ...
}

问题是我不能这样做,因为即使约束不同,也不能拥有具有相同签名的成员。但是,无法声明约束是 IComparableIComparable。所以,我不知道除了选择一个并使用它之外还能做什么。而且,无论我选择哪一个,我都会失去另一个,因为它们是独立的并且不会相互继承(这是有道理的)。

我是否遗漏了一些东西,有没有一种方法可以同时使用两者,或者我是否必须选择一个(可能是通用版本)?

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

凤舞天涯 2025-01-13 20:28:19

我根本不明白为什么第一种方法是通用的。为什么不只是:

public static bool IsBetween(this IComparable value, IComparable left, IComparable right)

使方法通用会增加什么价值?显然,您不会避免装箱惩罚,因为当您调用 CompareTo(object) 时,这些值将被装箱。

除非您有令人信服的理由使该方法通用,否则不要使其通用。然后它具有与其他方法不同的签名,您的问题就解决了。

I don't understand why the first method is generic at all. Why isn't it just:

public static bool IsBetween(this IComparable value, IComparable left, IComparable right)

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.

独夜无伴 2025-01-13 20:28:19

在 .NET 方法解析重载中,不考虑返回类型和泛型约束。因此,即使 IComparableIComparable 有一些共同点,仍然无法正常工作。只需选择 IComparable 版本即可。标准 .NET 类型(例如 Int32、Decimal、DateTime 等)无论如何都实现这两个接口。

In .NET method resolution overload doesn't take into account return types and generic constraints. So even if IComparable and IComparable<T> had something in common that would still not work. Just pick the IComparable<T> version. Standard .NET types such as Int32, Decimal, DateTime, ... implement both interfaces anyway.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文