如何最好重新编码这个示例扩展方法为所有数字类型的通用? [英] How should one best recode this example extension method to be generic for all numeric types?

查看:262
本文介绍了如何最好重新编码这个示例扩展方法为所有数字类型的通用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  public static float clip(this) float v,float lo,float hi)
{return Math.Max(lo,Math.Min(hi,v)); }

谢谢。

解决方案

  //用于实现IComparable的数值类型(如int和float)的IComparable约束public static T clip< T>(this T v,T lo,T hi)其中T:IComparable T 
{
//因为T实现了IComparable,我们可以使用CompareTo
if(v.CompareTo(lo)< 0)
v = lo; //确保v不是太低
if(v.CompareTo(hi)> 0)
v = hi; //确保v不是太高
return v;
}


How should one best recode this example extension method to be generic for all numeric types?

public static float clip(this float v, float lo, float hi)
{ return Math.Max(lo, Math.Min(hi, v)); }

Thanks.

解决方案

// IComparable constraint for numeric types like int and float that implement IComparable
public static T clip<T>(this T v, T lo, T hi) where T : IComparable<T>
{
  // Since T implements IComparable, we can use CompareTo
  if(v.CompareTo(lo)<0)
    v=lo; // make sure v is not too low
  if(v.CompareTo(hi)>0)
    v=hi; // make sure v is not too high
  return v;
}

这篇关于如何最好重新编码这个示例扩展方法为所有数字类型的通用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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