Using Roslyn for C#, how do I get a list of all properties that compose a return type?

北城余情 提交于 2019-12-23 08:48:18

问题


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.

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; }
}

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

Here is what I have already tried:

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

But this didn't work. Thanks in advance.


回答1:


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

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

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:

  • 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

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);


来源:https://stackoverflow.com/questions/21316952/using-roslyn-for-c-how-do-i-get-a-list-of-all-properties-that-compose-a-return

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!