Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set the generic variable of the type Type in a loop?

Tags:

c#

generics

I would like to do some similar process within a loop like this by calling a generic method with different types.

AAA, BBB are all classes. CreateProcessor is a generic method in the class of MyProcessor.

new List<Type> {typeof (AAA), typeof (BBB)}.ForEach(x =>
{
    var processor = MyProcessor.CreateProcessor<x>(x.Name);
    processor.process();
});

This doesn't compile, I got the error saying Cannnot resolve symbol x.

Technically, how to achieve it? (I know the strategy pattern is better...)

like image 267
zs2020 Avatar asked Jan 16 '14 00:01

zs2020


People also ask

How to make a variable a generic type?

Creating a simple generic type is straightforward. First, declare your type variables by enclosing a comma-separated list of their names within angle brackets after the name of the class or interface. You can use those type variables anywhere a type is required in any instance fields or methods of the class.

How to define a generic variable in Java?

A Generic Version of the Box Class To update the Box class to use generics, you create a generic type declaration by changing the code "public class Box" to "public class Box<T>". This introduces the type variable, T, that can be used anywhere inside the class.

How do you find the type of generic type?

Use the IsGenericType property to determine whether the type is generic, and use the IsGenericTypeDefinition property to determine whether the type is a generic type definition. Get an array that contains the generic type arguments, using the GetGenericArguments method.

What is a generic type parameter in Java?

A type parameter, also known as a type variable, is an identifier that specifies a generic type name. The type parameters can be used to declare the return type and act as placeholders for the types of the arguments passed to the generic method, which are known as actual type arguments.


2 Answers

Reflection is required to deal with the Type class:

    new List<Type> { typeof(AAA), typeof(BBB) }.ForEach(x => {
        var type = typeof(MyClass<>).MakeGenericType(x);
        dynamic processor = Activator.CreateInstance(type, x.Name);
        processor.process();
    });
like image 190
Hans Passant Avatar answered Oct 30 '22 17:10

Hans Passant


Sorry, I updated my question. I intended to call a generic method actually.

var method = typeof(MyProcessor).GetMethod("CreateProcessor", new Type[] { typeof(string) });
new List<Type> { typeof(AAA), typeof(BBB) }.ForEach(x =>
{
    dynamic processor = method.MakeGenericMethod(x).Invoke(null, new[] { x.Name });
    processor.process();
});
like image 41
MarcinJuraszek Avatar answered Oct 30 '22 17:10

MarcinJuraszek