简体   繁体   中英

A method with an unspecified number of Generic Type parameters

Is there a way to work with an unspecified number of Generic Type Parameters in a method?

Effectively what I want to do is something like this except for the obvious issue:

    private static void FetchChunk(int retries, KeyValuePair<List<dynamic>,Type>[] fetchfields)
    {
        try
        {
            foreach (var chunk in fetchfields)
            {
                var obj = chunk.Key;
                obj = DBRepository.GetAll<chunk.Value>().ToList();
            }
        }
        catch
        {
            //do stuff
        }

    }

However this fails because instead of Type, I need to use a Generic Type paramater such as T

The problem is however, I don't know how use generics in such a way to achieve what I am trying to achieve. Since I would want a unique generic type parameter for each KeyValuePair in the array.

This on the other hand, absolutely compiles, but doesn't do what I am intending which is each KeyValue pair would have it's own unique Generic Type parameters.

    private static void FetchChunk<T>(int retries, KeyValuePair<List<dynamic>, T>[] fetchfields)
    {
        try
        {
            foreach (var chunk in fetchfields)
            {
                var obj = chunk.Key;
                obj = DBRepository.GetAll<T>().ToList();
            }
        }
        catch
        {
            //do stuff
        }

The method signature of GetAll is

 public static IEnumerable<dynamic> GetAll(Type type, string columnNames = "*")

This doesn't work either:

                var type = chunk.Value.GenericTypeArguments[0];
                obj = DBRepository.GetAll<type>().ToList();

Is there a way to re-code this method in order to achieve my intentions?

If you can use reflection in the wrapping method then as described in the following answer you should be able to construct the instance of the generic method using MakeGenericMethod and then call it with different set of types.

Code updated to match the latest comment from @AlexanderRyanBaggett

private static void FetchChunk(int retries, KeyValuePair<List<dynamic>, Type>[] fetchfields)
{
    try
    {
        foreach (var chunk in fetchfields)
        {
            var method = typeof(DBRepository).GetMethod("GetAll");
            var Generic = method.MakeGenericMethod(chunk.Value);
            chunk.Key.AddRange(Generic.Invoke(null, null) as IEnumerable<dynamic>);
        }
    }
    catch
    {
        //do stuff } }
    }
}

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