简体   繁体   English

用T4模板反射

[英]Reflection with T4 Templates

I have a model class called VideoGame . 我有一个名为VideoGame的模型类。 I need the class to get passed in a t4 template using reflection in this method. 我需要在该方法中使用反射在t4模板中传递该类。

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?). 我收到一条错误消息:找不到类型或名称空间名称“类型”(您是否缺少using指令或程序集引用?)。 What I need to know is how to pass the VideoGame class inside that typeof() method. 我需要知道的是如何在该typeof()方法内传递VideoGame类。 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. typeof(modelName.GetType())将永远无法工作,因为modelName.GetType()返回System.String的运行时类型。

modelName.GetType has the same problem. modelName.GetType有相同的问题。

typeof(modelName) won't work because modelName is a string and typeof expects a Type. typeof(modelName)不起作用,因为modelName是一个字符串,并且typeof需要类型。

So....if you have a string "VideoGame" and you want to get the methods on the Type VideoGame.... 所以...。如果您有字符串“ VideoGame”,并且想要获取类型为VideoGame的方法。

I would do: 我会做:

Type.GetType(modelName).GetMethods()

Type.GetType will return a Type by the specified name. Type.GetType将返回具有指定名称的Type。 NOTE that this requires an Assembly Qualified Name....so just supplying VideoGame isn't enough. 请注意,这需要一个程序集合格名称...。因此仅提供VideoGame是不够的。 You need modelName to be in the form: 您需要modelName的形式为:

MyNamespace.VideoGame, MyAssemblyThatContainsVideoGame

Further, that means that whatever is running your T4 code needs to have a reference to MyAssemblyThatContainsVideoGame. 此外,这意味着无论正在运行的T4代码是什么,都需要引用MyAssemblyThatContainsVideoGame。

如果要将名称作为字符串传递,请使用Activator.CreateInstance

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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