如果使用单词更难解释,让我们看一个例子,我有一个像这样的泛型函数
void FunctionA<T>() where T : Form, new()
{
}
Run Code Online (Sandbox Code Playgroud)
如果我有反射类型,如何将其与上述功能一起使用?我很期待这样做
Type a = Type.GetType("System.Windows.Forms.Form");
FunctionA<a>();
Run Code Online (Sandbox Code Playgroud)
原因上述方法不起作用.
小智 13
你不能.必须在编译时解析.NET中的泛型.你正试图做一些能在运行时解决它们的事情.
您唯一能做的就是为FunctionA提供一个带有类型对象的重载.
嗯......他是对的.
class Program
{
static void Main(string[] args)
{
var t = typeof(Foo);
var m = t.GetMethod("Bar");
var hurr = m.MakeGenericMethod(typeof(string));
var foo = new Foo();
hurr.Invoke(foo, new string[]{"lol"});
Console.ReadLine();
}
}
public class Foo
{
public void Bar<T>(T instance)
{
Console.WriteLine("called " + instance);
}
}
Run Code Online (Sandbox Code Playgroud)
dev*_*evi 12
class Program
{
static void Main(string[] args)
{
int s = 38;
var t = typeof(Foo);
var m = t.GetMethod("Bar");
var g = m.MakeGenericMethod(s.GetType());
var foo = new Foo();
g.Invoke(foo, null);
Console.ReadLine();
}
}
public class Foo
{
public void Bar<T>()
{
Console.WriteLine(typeof(T).ToString());
}
}
Run Code Online (Sandbox Code Playgroud)
它动态地工作,s可以是任何类型
几年后来自msdn博客,但这可能会有所帮助:
Type t = typeof(Customer);
IList list = (IList)Activator.CreateInstance((typeof(List<>).MakeGenericType(t)));
Console.WriteLine(list.GetType().FullName);
Run Code Online (Sandbox Code Playgroud)