我想通过调用具有不同类型的泛型方法,在循环中进行类似的处理。
AAA,BBB都是类。CreateProcessor是MyProcessor类中的一个泛型方法。
new List<Type> {typeof (AAA), typeof (BBB)}.ForEach(x =>
{
var processor = MyProcessor.CreateProcessor<x>(x.Name);
processor.process();
});这不是编译,我看到了一个错误:Cannnot resolve symbol x。
从技术上讲,如何做到这一点?(我知道战略模式更好.)
发布于 2014-01-16 00:34:07
抱歉我更新了我的问题。实际上,我打算调用一个泛型方法。
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();
});发布于 2014-01-16 00:19:50
处理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();
});发布于 2014-01-16 00:17:59
这就是如何仅使用类型信息创建一个新变量,通过使用dynamic,您可以调用所有类型都存在的任何方法。我建议(假设这些类型是您自己的类)您应该实现一个接口baseclass或类似的东西,如果可能的话,它可以简化您的很多.
new List<Type> { typeof(string), typeof(int) }.ForEach(x =>
{
dynamic processor = Activator.CreateInstance(x);
processor.ToString();
processor.CallAnyMethodHere();
processor.Process();
});编辑的代码-添加一个明确的示例
using System;
using System.Collections.Generic;
using System.Reflection;
using System.Text;
public class mainClass
{
public static void Main(string[] args)
{
new List<Type> { typeof(StringBuilder), typeof(Int64) }.ForEach(x =>
{
dynamic instance = Activator.CreateInstance(x);
DoSomething(instance);
});
Console.ReadKey();
}
public static void DoSomething(StringBuilder stringBuilder)
{
Console.WriteLine("StringBuilder overload");
}
public static void DoSomething(Int64 int64)
{
Console.WriteLine("Int64 overload");
}
}编辑2-只调用泛型方法
using System;
using System.Collections.Generic;
using System.Reflection;
using System.Text;
using System.Linq;
public class mainClass
{
public static void Main(string[] args)
{
new List<Type> { typeof(StringBuilder), typeof(Int64) }.ForEach(x =>
{
var methodInfoArray = typeof(mainClass).GetMethods();
var methodInfo = methodInfoArray.First(mi => mi.Name == "DoSomething" && mi.IsGenericMethodDefinition);
var genericMethod = methodInfo.MakeGenericMethod(new Type[] { x });
var blah = genericMethod.Invoke(null, new object[] { "Hello" }) as MethodInfo;
});
Console.ReadKey();
}
public static void DoSomething<T>(string variable)
{
Console.WriteLine("DoSomething<T> " + typeof(T) + " overload - " + variable);
}
public static void DoSomething(string variable)
{
Console.WriteLine("DoSomething - " + variable);
}
}https://stackoverflow.com/questions/21150999
复制相似问题