我想通过调用不同类型的泛型方法在这样的循环中做一些类似的过程.
AAA,BBB都是班级.CreateProcessor是类中的通用方法MyProcessor.
new List<Type> {typeof (AAA), typeof (BBB)}.ForEach(x =>
{
var processor = MyProcessor.CreateProcessor<x>(x.Name);
processor.process();
});
Run Code Online (Sandbox Code Playgroud)
这不编译,我得到错误说Cannnot resolve symbol x.
从技术上讲,如何实现呢?(我知道策略模式更好......)
处理Type类需要反射:
new List<Type> { typeof(AAA), typeof(BBB) }.ForEach(x => {
var type = typeof(MyClass<>).MakeGenericType(x);
dynamic processor = Activator.CreateInstance(type, x.Name);
processor.process();
});
Run Code Online (Sandbox Code Playgroud)
对不起,我更新了我的问题.我打算实际上调用泛型方法.
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();
});
Run Code Online (Sandbox Code Playgroud)