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;
}
精彩评论