开发者

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

How should one best recode this example extension method to be generic for all nu开发者_StackOverflowmeric 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;
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜