我想通过字符串名称创建一个 Controller 的新实例。在经典的 ASP 中我会做一个 eval,但是如何在 C# 中做呢?
例如:
如果我想创建“AccountController”的实例,通常我会这样写:
var Acc = new AccountController();
现在如果 Controller 名称只能作为字符串使用,我该如何实例化该对象?
例如,
var controllerName = "AccountController";
var acc = new eval(controllerName)();
感谢您的帮助!
弗兰克
最佳答案
如果您的 Controller 在程序集中,您只需要一个类名,否则您需要一个完全限定的名称(命名空间 和 程序集)。你会用反射来做。像这样的东西:
Type t = Type.GetType("NameOfController");
var c = Activator.CreateInstance(t);
还有其他方法,但都涉及到反射(System.Reflection
)。
关于c# mvc 从字符串名称动态创建 Controller - eval?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1789971/