问题
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