Question:
I created a VSIX project to read properties of a class, trying to get their names and varriable types as doing sth like below using Roslyn;string filePath = Path.GetDirectoryName(dte.Solution.FullName) + @"\ProjectName\Models\Products.cs";
string fileBody = File.ReadAllText(filePath);
var tree = CSharpSyntaxTree.ParseText(fileBody);
var root = tree.GetRoot();
var nodes = root.DescendantNodes();
foreach (var node in Properties)
{
// How to get;
// Get name of the property
// Get type of property int, string, double etc...
}
Could you please provide correct way of doing that?Answer:
No help, but I found the answer, I put here if someone needs it, foreach (var node in nodes)
{
var properties = node.DescendantNodes().OfType<PropertyDeclarationSyntax>();
foreach (var property in properties)
{
Field field = new Field();
field.Type = property.Type.ToString();
field.Name = property.Identifier.ValueText;
field.Modifier = property.Modifiers.ToString();
if (property.AttributeLists.Count > 0)
{
foreach (var item in property.AttributeLists)
{
Attribute attribute = new Attribute();
attribute.FullString = item.Attributes.ToFullString().ToLower();
if (item.Attributes.First().ArgumentList != null)
attribute.Value = item.Attributes.First().ArgumentList.Arguments.First().ToFullString();
field.Attributes.Add(attribute);
}
}
model.Fields.Add(field);
}
}
And my model to capture it; public class Field
{
public string Name { get; set; }
public string Type { get; set; }
public string Modifier { get; set; }
public List<Attribute> Attributes { get; set; } = new List<Attribute>();
}
public class Attribute
{
public string Key { get; set; }
public string Value { get; set; }
public string FullString { get; set; }
}
public class Model
{
public string Name { get; set; }
public List<Field> Fields { get; set; } = new List<Field>();
public ModelTypes ModelType { get; set; }
}
If you have better answer, please add a comment about this, thank you!
If you like this answer, you can give me a coffee by <a href=”https://violencegloss.com/mkw7pgdwwr?key=2a96ade6f3760c7e63343a320febb78e”>click here</a>
Source: Stackoverflow.com
Leave a Review