开发者

Reflection with T4 Templates

开发者 https://www.devze.com 2023-04-07 11:46 出处:网络
I have a model class called VideoGame. I need the class to get passed in a t4 template using reflection in this method.

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


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.


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


The import of the classes in a T4 template is pretty awkward. I had this problem too and found it easier to write a console program that simply references the assembly where the classes are in, and puts out everything on the console. A text file can be created just as easily of course.

0

精彩评论

暂无评论...
验证码 换一张
取 消