简体   繁体   中英

How can i cast System.Type in MVC Controller?

So, i need to get an area of a controller, and i'm getting the controllers with this way:

var assembly = System.Reflection.Assembly.GetCallingAssembly();
var controllers = from type in assembly.GetTypes()
                  where type.Name.Contains("Controller")
                  select type;

Ok, with this way i've all controllers, but they are as Type, how can i cast in a MVC Controller? 'Cause i need to get the controller area with somthing like that:

string area = controller.ControllerContext.RouteData.DataTokens["area"].ToString();

So?

You cannot cast a Type to an instance of an object. This doesn't make sense. You might inspect the namespace into which this type is defined by looking at the type.FullName and is the only way to understand in which Area the controller that this Type represents is defined in. By the way checking that a given type is a controller using type.Name.Contains("Controller") seems pretty brittle and fragile. You'd better use where typeof(Controller).IsAssignableFrom(type);

您可以使用创建类型的对象

Activator.CreateInstance(type);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM