[英]C# use generic invoke as MVC ActionResult
I have an Action in ASP.NET MVC4 that uses a generic method: 我在ASP.NET MVC4中有一个使用泛型方法的Action:
public ActionResult Test1()
{
return Generic<TestClass>();
}
public ActionResult Test2(string className)
{
MethodInfo method = typeof(ConfigController).GetMethod("Generic");
MethodInfo generic = method.MakeGenericMethod(Type.GetType(className));
generic.Invoke(this, null);
return null; // Generic<TestClass>();
}
public ActionResult Generic<T>() where T : new()
{
DatabaseUtil db = new DatabaseUtil();
ViewBag.ClassName = typeof(T).AssemblyQualifiedName;
return View("~/Views/Config/GenericConfig.cshtml", db.SelectAll<T>());
}
Test1() works just as expected, it passes along the TestClass
to the generic method and returns the view using the model of appropriate objects. Test1()按预期工作,它将
TestClass
传递给泛型方法,并使用适当对象的模型返回视图。
I want to take this a step further and just pass the class name as a string so that I don't need a specific action for each type I want to use. 我想更进一步,只是将类名作为字符串传递,这样我就不需要为我想要使用的每种类型执行特定的操作。
Test2() works up to the point where I return the view. Test2()工作到我返回视图的位置。 I know the
invoke
is working, as I hit a breakpoint in Generic<T>
with the correct class type, but the return from Test2() is still what's passed back to the browser. 我知道
invoke
正在工作,因为我使用正确的类类型在Generic<T>
了断点,但是从Test2()返回的仍然是传回给浏览器的。
How can I delegate the return to the generically invoked ActionResult
method? 如何将返回委托给一般调用的
ActionResult
方法?
It was right in front of me (still new to reflection): 它就在我面前(对于反思来说还是新手):
public ActionResult Test(string className)
{
MethodInfo method = typeof(ConfigController).GetMethod("Generic");
MethodInfo generic = method.MakeGenericMethod(Type.GetType(className));
ActionResult ret = (ActionResult)generic.Invoke(this, null);
return ret;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.