簡體   English   中英

Roslyn - 如何使用 Roslyn 在 class 中獲取屬性名稱和類型?

[英]Roslyn - how to get property names and types in a class 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...
        }

你能提供正確的方法嗎?

沒有幫助,但我找到了答案,如果有人需要,我會放在這里,

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

還有我的 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