获取 cshtml 文件的语义模型? [英] Getting a SemanticModel of a cshtml file?

查看:68
本文介绍了获取 cshtml 文件的语义模型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用 Roslyn 在 Razor 视图内的 C# 代码块的上下文中分析语义信息.

有没有办法(在 Visual Studio 2015 中,甚至在单元测试中)获取表示此代码的 SemanticModel?

解决方案

Razor 文件包含一个 C# 投影缓冲区,其中包含生成的 C# 代码(包括您不是自己编写的部分).此缓冲区具有完整的 Roslyn 服务,正是您要寻找的.

你需要遍历TextView的BufferGraph,找到CSharp缓冲区;然后你可以得到它的Document和语义模型.

如果您从光标位置开始,您只需将该位置映射到 CSharp 缓冲区.

请注意,TextView 包含多个 CSharp 缓冲区是完全合法的.(虽然 Razor 编辑器永远不会那样做)

<小时>

如果您不在 TextView 中工作,则需要自己完成所有这些工作;您需要通过 Razor 编译器运行 Razor 源代码以获取生成的 C# 源代码,然后使用 Roslyn 对其进行编译以获得语义模型.

I'd like to use Roslyn to analyze semantic information within the context of a block of C# code inside a Razor View.

Is there any way (within Visual Studio 2015, or even in a unit test) to get the SemanticModel that represents this code?

解决方案

Razor files contain a C# projection buffer with the generated C# code (including the parts that you don't write yourself). This buffer has full Roslyn services and is exactly what you're looking for.

You need to walk through the TextView's BufferGraph and find the CSharp buffer; you can then get its Document and semantic model.

If you're starting from the cursor location, you need simply need to map that location to a CSharp buffer.

Note that it is perfectly legal for a TextView to contain multiple CSharp buffers. (although the Razor editor will never do that)


If you aren't working in a TextView, you need to do all of this yourself; you need to run the Razor source through the Razor compiler to get the generated C# source, then compile that with Roslyn to get a semantic model.

这篇关于获取 cshtml 文件的语义模型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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