如果你有一个字符串,那么首先要做的是Type.GetType(string),或者(最好)Assembly.GetType(string)获取Type实例.从那里,你需要使用反射:
Type type = someAssembly.GetType(typeName);
typeof(TypeWithTheMethod).GetMethod("SomeGenericFunction")
.MakeGenericMethod(type).Invoke({target}, new object[] {objectID});
Run Code Online (Sandbox Code Playgroud)
其中{target}是实例方法的实例,以及null静态方法.
例如:
using System;
namespace SomeNamespace {
class Foo { }
}
static class Program {
static void Main() {
string typeName = "SomeNamespace.Foo";
int id = 123;
Type type = typeof(Program).Assembly.GetType(typeName);
object obj = typeof(Program).GetMethod("SomeGenericFunction")
.MakeGenericMethod(type).Invoke(
null, new object[] { id });
Console.WriteLine(obj);
}
public static T SomeGenericFunction<T>(int id) where T : new() {
Console.WriteLine("Find {0} id = {1}", typeof(T).Name, id);
return new T();
}
}
Run Code Online (Sandbox Code Playgroud)