Reflection with T4 Templates

佐手、 提交于 2019-12-11 03:44:48

问题


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);

回答1:


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.




回答2:


If you want to pass the name as string use Activator.CreateInstance



来源:https://stackoverflow.com/questions/7558809/reflection-with-t4-templates

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!