Search code examples
c#asp.net-mvctemplatest4

Reflection with T4 Templates


I have a model class called VideoGame. I need the class to get passed in a t4 template using reflection in this method.

MethodInfo[] methodInfos =
    typeof(type).GetMethods(BindingFlags.Public | BindingFlags.Static);

I have the following variables.

//passed via powershell file - is a string "VideoGame"
var modelName = Model.modelName
Type type = modelName.GetType();

I get an error that says: The type or namespace name 'type' could not be found (are you missing a using directive or an assembly reference?). What I need to know is how to pass the VideoGame class inside that typeof() method. I have tried the following:

MethodInfo[] methodInfos =
    typeof(modelName.GetType()).GetMethods(BindingFlags.Public | BindingFlags.Static);
MethodInfo[] methodInfos =
    modelName.GetType.GetMethods(BindingFlags.Public | BindingFlags.Static);
MethodInfo[] methodInfos =
    typeof(modelName).GetMethods(BindingFlags.Public | BindingFlags.Static);

Solution

  • typeof(modelName.GetType()) would never work, because modelName.GetType() returns a System.String's runtime type.

    modelName.GetType has the same problem.

    typeof(modelName) won't work because modelName is a string and typeof expects a Type.

    So....if you have a string "VideoGame" and you want to get the methods on the Type VideoGame....

    I would do:

    Type.GetType(modelName).GetMethods()
    

    Type.GetType will return a Type by the specified name. NOTE that this requires an Assembly Qualified Name....so just supplying VideoGame isn't enough. You need modelName to be in the form:

    MyNamespace.VideoGame, MyAssemblyThatContainsVideoGame
    

    Further, that means that whatever is running your T4 code needs to have a reference to MyAssemblyThatContainsVideoGame.