问题描述
我有一个名为的VideoGame
模型类。我需要的类在这个方法中使用反射获得通过在T4模板。
的MethodInfo [] = methodInfos
typeof运算(类型).GetMethods(BindingFlags.Public | BindingFlags.Static);
我有以下变量。
//通过PowerShell的文件中传递 - 是一个字符串的VideoGame
VAR MODELNAME = Model.modelName
类型type = modelName.GetType();
我得到一个错误,指出:类型或命名空间名称'类型'找不到(是否缺少using指令或程序集引用?)。我需要知道的是如何传递的typeof()方法中视频游戏类。我曾尝试以下内容:
的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())永远不会成功,因为modelName.GetType()返回以System.String的运行时类型。
modelName.GetType有同样的问题。
typeof运算(MODELNAME)不会起作用,因为MODELNAME是字符串,typeof运算需要一个类型。
所以....如果你有一个字符串的VideoGame,你想要得到的类型的VideoGame方法....
我会做:
Type.GetType(MODELNAME).GetMethods()
Type.GetType将由指定名称返回一个类型。请注意,这需要一个大会限定名称....所以才提供的VideoGame是不够的。你需要MODELNAME是形式:
MyNamespace.VideoGame,MyAssemblyThatContainsVideoGame
此外,这意味着,无论是运行您的T4 code需要具有MyAssemblyThatContainsVideoGame一个参考。
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.
这篇关于反射用T4模板的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!