简体   繁体   中英

Doing math in C# generic method (known with unknown)

Bonjorno, people. Could you please explain me how to perform operations inside a generic method. I want a random array of different unsigned integers. IDE doesn't allow me to multiply a Double (and others) with a generic struct. Typecasting doesn't work in any way I try. Maybe I'd better just stop "designing a bicycle" and call from the generic method one of several method for each integer type?

public static T[] getRandArray<T>(int amount) where T: struct
{
    FieldInfo maxValueField =
        typeof(T).GetField(
            "MaxValue",
            BindingFlags.Public | BindingFlags.Static
        );

    T maxValueOfT = (T)maxValueField.GetValue(null);

    Random randNum = new Random();

    T[] array = new T[amount];

    for (int i = 0; i < amount; i++)
    {
        array[i] = (T)(randNum.NextDouble()) * maxValueOfT;
    }

    return array;
}

It will not work with generics.

  • If you need only an uint[] as a result of your method then replace generic type with that.
  • If you need not only uint[] but an array of any other type, eg int[] then you have to create an overload for your method.

Unfortunately there is no constraint you could give for the generic type that would allow you to do some math with them.

Btw. I would suggest that you create an instance of Random as a static field in your static class and then use it in the method(s).

Only generic methods should be made generic. The only constraint defined there is T : struct. Suppose I define the following:

public struct Point 
{ 
    public int X { get; set; }
    public int Y { get; set; }
}

I can supply a Point to getRandArray, but how do you use it?

Rather, choose a type that meets your needs. If the interface you're supplying is appropriate, you can often still leverage implicit conversions to achieve your goal

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