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

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

问题描述

我试着写一篇关于数字类型的扩展方法以流利的测试框架我建设使用。基本上,我想这样做:

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

只是其中T:结构不这样做,因为这也将匹配字符串布尔,并有可能别的东西,我忘了。是有什么我可以做只匹配数字类型? (实现具体类型&GT; &LT; 运营商,这样我就可以对它们进行比较......如果这意味着我匹配的日期还有,它并不真正的问题 - 延长仍然会做什么,我希望)

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 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天全站免登陆