匹配数字类型的通用约束 [英] Generic constraint to match numeric types

查看:30
本文介绍了匹配数字类型的通用约束的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试编写一个关于数字类型的扩展方法,以在我正在构建的流畅测试框架中使用.基本上,我想这样做:

I'm trying to write an extension method on numeric types to be used in a fluent testing framework I'm building. Basically, I want to do this:

public static ShouldBeGreaterThan<T>(this T actual, T expected, string message)
    where T : int || T: double || etc...

只是 where T : struct 不做,因为它也将匹配 stringbool,可能还有别的东西我遗忘.我可以做些什么来只匹配数字类型?(特别是实现 >< 运算符的类型,所以我可以比较它们......如果这意味着我也在匹配日期,它不会真的很重要 - 扩展仍然会做我期望的.)

Just where T : struct doesn't do, since that will also match string and bool, and possibly something else I'm forgetting. is there something I can do to match only numeric types? (Specifically types that implement the > and < operators, so I can compare them... If this means I'm matching dates as well, it doesn't really matter - the extension will still do what I expect.)

推荐答案

在这种情况下,您希望将泛型限制为 IComparable 接口,它使您可以访问 CompareTo 方法,因为这界面允许您回答问题ShouldBeGreaterThan.

In this case you want to constrain your generic to the IComparable interface, which gives you access to the CompareTo method, since this interface allows you to answer the question ShouldBeGreaterThan.

数字类型将实现该接口,而且它也适用于字符串的事实不应该那么困扰您.

Numeric types will implement that interface and the fact that it also works on strings shouldn't bother you that much.

这篇关于匹配数字类型的通用约束的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆