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...)
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.
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.
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.
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.
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();
});
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();
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With