开发者

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

开发者 https://www.devze.com 2023-03-29 07:54 出处:网络
How should one best recode this example extension method to be generic for all nu开发者_StackOverflowmeric 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

精彩评论

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