简体   繁体   English

Roslyn - 如何使用 Roslyn 在 class 中获取属性名称和类型?

[英]Roslyn - how to get property names and types in a class using Roslyn?

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;我创建了一个 VSIX 项目来读取 class 的属性,尝试使用 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?你能提供正确的方法吗?

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;还有我的 model 来捕捉它;

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM