简体   繁体   中英

Multiple data type input in C# function

I am switching from an Arduino (c language) to a Netduino (c# language).

In my arduino program I have the following function (built-in):

Constrain

I would like to convert this to C#. I have the following code:

int ConstrainValue(int value, int min, int max)
    {
        int Value = value;
        int Min = min;
        int Max = max;

        if (Value >= Max)
        {
            Value = Max;
            return Value;
        }
        else if (Value <= Max)
        {
            Value = Min;
            return Value;
        }
        return Value;
    }

However, I would also like to be able to use this for the double datatype. Is it possible to modify the function so multiple datatypes can be used?

It is, using IComparable .

static T ConstrainValue<T>(T value, T min, T max) where T : IComparable
{
    if (value.CompareTo(max) > 0)
        return max;
    else if (value.CompareTo(min) < 0)
        return min;
    return value;
}

Yes it is, you need to make it a generic function, something like that:

T ConstrainValue<T>(T value, T min, T max) where T : IComparable

I think you'll need to add some more interfaces though

By specifying struct , you will not get boxing when calling the method, but by using IComparable you will still get it when calling CompareTo because that interface method takes an object .

So use IComparable<T> and I'm pretty sure there's no boxing now:

    private static T ConstrainValue<T>(T value, T min, T max)
      where T : struct, IComparable<T>
    {
        if (value.CompareTo(max) > 0)
        {
            return max;
        }

        if (value.CompareTo(min) < 0)
        {
            return min;
        }

        return value;
    }

By using generics you can use multiple datatypes

T ConstrainValue(T value, T min, T max) where T : IComparable

.net micro (netduino) does NOT support generics as of v4.2.

You would have to use another scheme such as a function that takes objects as arguments and then does the work. You'll then have to use 'as' or casting on the return in the calling function:

    object ConstrainValueInt(object value, object min, object max)
        {
   /* this could still get you in trouble with bool type */
          if (value.GetType().isValueType && min.GetType().isValueType && max.GetType().isValueType )
          return ( (value >= max)? max : ((value <= min)? min : value));
        }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM