我有基本上看起来像一个名为test.cs中一个cs文件:
I've got a .cs file named 'test.cs' which essentially looks like:
namespace test
{
public class TestClass
{
public void Hello()
{
var x = 1;
}
}
}
我试图解析这与罗斯林,并得到x的类型,它应该是'诠释',但我只能找出它的输入'变种',我似乎无法得到实际的基本类型
I'm trying to parse this with Roslyn and get the type of x, which should be 'int', but I can only find out that it's type 'var', I can't seem to get the actual underlying type.
下面这基本上是我的code是现在
Here's basically what my code is now
var location = "test.cs";
var sourceTree = CSharpSyntaxTree.ParseFile(location);
var root = (CompilationUnitSyntax)sourceTree.GetRoot();
foreach (var member in root.Members)
{
//...get to a method
var method = (MethodDeclarationSyntax())member;
foreach (var child in method.Body.ChildNodes())
{
if (child is LocalDeclarationStatementSyntax)
{
//var x = 1;
child.Type.RealType()?
}
}
}
我怎样才能得到孩子的真正的类型?我已经看到了一些东西,说我应该使用SemanticModel或解决方案或工作空间,但我似乎无法找出如何加载我与罗斯林的测试解决方案,然后得到的X型。
How can I get the real type of child? I've seen some things saying I should use a SemanticModel or Solution or a Workspace, but I can't seem to find out how load my test solution with Roslyn and then get the type of 'x'.
另外,我一直没能找到任何真正的好罗斯林文档,这一切似乎为s $ P $垫中间选出了一堆不同的版本并没有什么适合初学者和我一样。有谁知道一个'介绍到罗斯林'或类似的快速入门,我可以读一下吗?
Also, I haven't been able to find any really good Roslyn documentation, it all seems to be spread out among a bunch of different versions and nothing for beginners like me. Does anyone know of an 'intro to Roslyn' or similar quickstart I could read up on?
要获得实际类型的变量声明为使用 VAR
,呼叫 GetSymbolInfo ()
在 SemanticModel
。您可以使用 MSBuildWorkspace
打开现有的解决方案,然后枚举其项目和他们的文件。用一个文件来获得它的 SyntaxRoot
和 SemanticModel
,然后查找 VariableDeclarations
和检索的符号为键入
这样的声明的变量:
To get the actual type for a variable declared using var
, call GetSymbolInfo()
on the SemanticModel
. You can open an existing solution using MSBuildWorkspace
, then enumerate its projects and their documents. Use a document to obtain its SyntaxRoot
and SemanticModel
, then look for VariableDeclarations
and retrieve the symbols for the Type
of a declared variable like this:
var workspace = MSBuildWorkspace.Create();
var solution = workspace.OpenSolutionAsync("c:\\path\\to\\solution.sln").Result;
foreach (var document in solution.Projects.SelectMany(project => project.Documents))
{
var rootNode = document.GetSyntaxRootAsync().Result;
var semanticModel = document.GetSemanticModelAsync().Result;
var variableDeclarations = rootNode
.DescendantNodes()
.OfType<LocalDeclarationStatementSyntax>();
foreach (var variableDeclaration in variableDeclarations)
{
var symbolInfo = semanticModel.GetSymbolInfo(variableDeclaration.Declaration.Type);
var typeSymbol = symbolInfo.Symbol; // the type symbol for the variable..
}
}
上一篇:使用useState钩子将项添加到存储在REACT状态的数组中的正确方法是什么?钩子、组中、正确、状态
下一篇:反应打字脚本故事书使用onChange回调实现定制的输入组件,然后将setState值返回到输入回调、脚本、组件、反应