将 Roslyn 用于 C#,如何获取组成返回类型的所有属性的列表? [英] Using Roslyn for C#, how do I get a list of all properties that compose a return type?

查看:49
本文介绍了将 Roslyn 用于 C#,如何获取组成返回类型的所有属性的列表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我从一组方法中查询了一个方法:

Let's say that I have queried a single method from a collection of methods:

var myMethod = someListofMethods.FirstOrDefault(m => m.Identifier.ValueText == myMethodName);

现在我想获取方法的返回类型...

Now I want to take the method's return type. . .

var returnType = myMethod.ReturnType;

...并确定(如果它不是原始类型)该类型中包含哪些属性.

. . .and determine (if it is not a primitive) what properties are contained within that type.

因此,例如,假设返回类型是定义的 FooObject:

So, for example let's say the return type is FooObject which is defined:

public class FooObject{
     public string Fizz {get; set; }
     public string Buzz {get; set; }
}

如何正确查询 FooObject 以获取其属性列表?

How do I properly interrogate FooObject for a list of it's properties?

这是我已经尝试过的:

returnType.DescendantNodes().OfType<PropertyDeclarationSyntax>();

但这没有用.提前致谢.

But this didn't work. Thanks in advance.

推荐答案

您正在查看抽象语法树 (AST) 代码级别.因此行:

You are looking at the abstract syntax tree (AST) level of code. Hence line:

returnType.DescendantNodes().OfType<PropertyDeclarationSyntax>();

什么都不返回.returnType 在这个上下文中是 AST 的 IdentifierNameSyntax 节点,只包含文本 FooObject.如果你想分析返回类型,你应该:

returns nothing. returnType in this context is IdentifierNameSyntax node of the AST, just containing text FooObject. If you want to analyze return type, you should:

  • returnType的角度解释语法树,找到返回类型的完整命名空间
  • 搜索低谷代码以找到此类型声明
  • 分析类型声明语法树以找到其所有属性
  • interpret syntax tree from returnType point of view to find full namespace of the return type
  • search trough code to find this type declaration
  • analyze type declaration syntax tree to find all its properties

但是,这实际上是编译器所做的,因此您可以将 Roslyn 的使用升级到编译级别,例如:

But, it is in fact what compiler does so you can go level up with Roslyn usage to the compilation level, for example:

var workspace = Workspace.LoadSolution(solutionName);
var solution = workspace.CurrentSolution;

var createCommandList = new List<ISymbol>();
var @class = solution.Projects.Select(s => s.GetCompilation()
                                            .GetTypeByMetadataName(className))
                              .FirstOrDefault();
var method = @class.GetMembers(methodName)
                    .AsList()
                    .Where(s => s.Kind == CommonSymbolKind.Method)
                    .Cast<MethodSymbol>()
                    .FirstOrDefault();
var returnType = method.ReturnType as TypeSymbol;
var returnTypeProperties = returnType.GetMembers()
                                     .AsList()
                                     .Where(s => s.Kind == SymbolKind.Property)
                                     .Select(s => s.Name);

这篇关于将 Roslyn 用于 C#,如何获取组成返回类型的所有属性的列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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