Reputation: 881
I'm trying to find out if there is a way to get the inner details of the TYPE of a method parameter.
Say a method has the below definition
public void method1(Type1 param1, Type2 param2)
{
...
...
}
And Type1
has the below definition
public class Type1
{
public int prop1 {get; set;}
public string prop2 {get; set;}
public double prop3 {get; set;}
}
Then what I'm looking to get out of my sample tool is the list of properties of the class Type1
. That is, I'm expecting my output to be
prop1
prop2
prop3
I could get a reference to the parameter by doing a param.Type
but it is of type IdentifierNameSyntax
. I'm able to get the name from it (Type1
in this case) but not able to dig deeper INTO Type1
to get the properties.
Is there any simple way to get that which I'm not yet aware of? Or do I have to do a search in the entire solution again using the name of the type that I got?
Thanks a lot!
P.S.: I did get a thought of using Reflection
but all I have is a string (Type1
) and not the actual TYPE. Not sure if I can use this or not.
Update-1: This question seems to be mildly close to what I'm expecting but from what I understand, the user only wants the name of the parameter type, not it's inner details.
Update-2: Adding sample code from my tool below. Unfortunately, I cannot post the actual code but the below sample is basically what I'm trying to do. Update-2: Adding sample code from my tool below. Unfortunately, I cannot post the actual code but the below sample is basically what I'm trying to do.
var methodNode = (MethodDeclarationSyntax)node;
string paramClassName = string.Empty;
foreach (var param in methodNode.ParameterList.Parameters)
{
paramClassName = param.Type.ToFullString();
//GET Class details from the above class name
GetInnerDetailsOfClassFromClassName(paramClassName); //any way to do this?
}
Upvotes: 2
Views: 1759
Reputation: 881
Thanks to @Serj-Tm, @KevinPilch-Bisson and @JonSkeet. Your suggestions of using Symbols worked. This is my code below that returned the result I was expecting.
var methodNode = (MethodDeclarationSyntax)node;
string modelClassName = string.Empty;
foreach (var param in methodNode.ParameterList.Parameters)
{
var metaDataName = document.GetSemanticModelAsync().Result.GetDeclaredSymbol(param).ToDisplayString();
//'document' is the current 'Microsoft.CodeAnalysis.Document' object
var members = document.Project.GetCompilationAsync().Result.GetTypeByMetadataName(metaDataName).GetMembers();
var props = (members.OfType<IPropertySymbol>());
//now 'props' contains the list of properties from my type, 'Type1'
foreach (var prop in props)
{
//some logic to do something on each proerty
}
}
Hope this helps!
Upvotes: 0
Reputation: 11615
Once you find the ParameterSyntax
, use SemanticModel.GetDeclaredSymbol
to get the IParameterSymbol
, and then look at its Type
to get the ITypeSymbol
you are interested in.
Upvotes: 3