无法从T4模板中获取VCCodeModel [英] Can't get VCCodeModel from within a T4 template

查看:51
本文介绍了无法从T4模板中获取VCCodeModel的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些C#代码可以访问VC ++项目.现在,我试图从正在阅读的内容生成C#代码.

原始程序使用以下方法查看打开的VS实例,并在其中查找特定文件:

I have some C# code that accesses a VC++ project. Now I'm trying to generate C# code from what I'm reading.

The original program looks at open VS instances, and looks for a particular file in them, using:

            docToParse = dte.Solution.FindProjectItem(nameOfDocToParse);
            VCCodeModel cm = docToParse.ContainingProject.CodeModel as VCCodeModel;


(第一行在try/catch块中.)

这可以正常工作,并且我可以获取所有想要的数据.顺便说一句,我发现如果仅获得FileCodeModel,就无法将其转换为VCCodeModel,这就是为什么我要去该项目.

现在,我正在尝试从T4模板.我已经将C ++项目添加为与我从中进行T4生成的解决方案相同的项目.我正在使用以下代码来尝试访问该项目的VCCodeModel.它与以前完全相同,只是我得到的DTE不同,并且它属于当前VS实例,而不是另一个实例.


(The first line is within a try/catch block.)

This works fine, and I'm able to get all the data I want. BTW, I found that if I just get the FileCodeModel, I can't cast it to VCCodeModel, which is why I'm going to the project.

Now I'm trying the same thing from a T4 template. I've added the C++ project as a project of the same solution I'm doing T4 generation from. I'm using the following code to attempt to get access to the VCCodeModel of that project. It's exactly the same as before, except I'm getting the DTE differently, and it belongs to the current VS instance, instead of another one.

	DTE2 dte = (Host as IServiceProvider).GetService(typeof(DTE)) as DTE2;
	ProjectItem docToParse = dte.Solution.FindProjectItem(nameOfDocToParse);
	VCCodeModel cm = docToParse.ContainingProject.CodeModel as VCCodeModel;



问题是,将docToParse.ContainingProject.CodeModel(不为null)转换为VCCodeModel失败,给了我null.

有什么想法吗?



The problem is, the casting of docToParse.ContainingProject.CodeModel (which is not null) to VCCodeModel fails, giving me null.

Any ideas? Thanks!

推荐答案

如果对象不是预期的类型,则operator返回null.如果使用以下代码

VCCodeModel cm =(VCCodeModel)docToParse.ContainingProject.CodeModel

,并且该对象不是预期的类型,则将得到一个异常,该异常将告诉你实际的类型是什么.您也许可以使用此信息来查找问题.
The "as" operator returns null if the object is not of the expected type. If you use the following code

VCCodeModel cm = (VCCodeModel)docToParse.ContainingProject.CodeModel

and the object is not of the expected type, you will get an exception that will tell you what the actual type is. You may be able to use this information to find the problem.


这篇关于无法从T4模板中获取VCCodeModel的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆