[英]How to implement generic method in C# having multiple constraints
I want to write a generic method: 我想写一个通用的方法:
void Foo<T>(IList<T> list)
In the method, I want to compare elements of list either by using operator < if T is primitive type or Compare() if T implements IComparable. 在该方法中,我想通过使用operator <if T是原始类型来比较列表的元素,或者如果T实现IComparable则比较Compare()。
Is this possible? 这可能吗? If not, it means C# generics is very limited in use I think.
如果没有,这意味着我认为C#泛型的使用非常有限。
Is this possible?
这可能吗? If not, it means C# generics is very limited in use I think.
如果没有,这意味着我认为C#泛型的使用非常有限。
Even if it weren't possible, generics can be used in many many situations. 即使它是不可能的,仿制药可以在很多很多情况下使用。
However, it's really simple given that all the primitive types implement IComparable<T>
; 但是,由于所有原始类型都实现了
IComparable<T>
,因此它非常简单;
void Foo<T>(IList<T> list) where T : IComparable<T>
{
T x = ...;
T y = ...;
if (x.CompareTo(y) < 0)
{
...
}
}
Note that this will not introduce boxing operations. 请注意,这不会引入装箱操作。 I'd expect the JITted code for primitive types to end up having very similar performance to hardcoding it to use
<
or >
. 我希望原始类型的JITted代码最终具有与使用
<
或>
进行硬编码非常相似的性能。
Now this is a slightly special case, because there's an interface which is roughly equivalent to those operators. 现在这是一个稍微特殊的情况,因为有一个接口大致相当于那些运算符。 What isn't as easy is using arithmetic operators (
+
, -
etc). 使用算术运算符(
+
, -
etc) 并不容易。 See the article on my web site for a few approaches to this. 请参阅我的网站上的文章,了解一些方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.