gpt4 book ai didi

c# - 从磁盘上的 .cs 类文件获取属性

转载 作者:太空狗 更新时间:2023-10-30 01:30:41 26 4
gpt4 key购买 nike

我正在为 Visual Studio 编写 VSIX 扩展。使用该插件,用户可以从他在 VS 中的解决方案资源管理器中选择一个类文件(因此是磁盘上某处的实际 .cs 文件),然后通过触发我的 VSIX 代码对该文件执行特定操作上下文菜单项。

我的 VSIX 扩展需要知道所选类文件的 publicinternal 属性是什么。

我试图通过使用正则表达式来解决这个问题,但我有点坚持使用它。我不知道如何只获取类的属性名称。它现在发现的太多了。

这是我目前的正则表达式:

\s*(?:(?:public|internal)\s+)?(?:static\s+)?(?:readonly\s+)?(\w+)\s+(\w+)\s*[^(]

演示:https://regex101.com/r/ngM5l7/1从这个演示中我想提取所有的属性名称,所以:

Brand,
YearModel,
HasRented,
SomeDateTime,
Amount,
Name,
Address

附言。我知道正则表达式不是这种工作的最佳选择。但我认为我没有 VSIX 扩展的任何其他选项。

最佳答案

how to only get the property names of the class.

此模式已注释,因此使用 IgnorePatternWhiteSpace作为一种选择或删除所有评论并加入一行。

但此模式获取您在示例中提供的所有数据

(?>public|internal)     # find public or internal
\s+ # space(s)
(?!class) # Stop Match if class
((static|readonly)\s)? # option static or readonly and space.
(?<Type>[^\s]+) # Get the type next and put it into the "Type Group"
\s+ # hard space(s)
(?<Name>[^\s]+) # Name found.
  1. 找到六个匹配项(见下文)。
  2. 从命名匹配捕获中提取数据 (?<Named> ...)例如mymatch.Groups["Named"].Value或硬整数。
  3. 在这种情况下,“类型”和“名称”是组名或索引或硬整数。
  4. 将在注释掉的部分中找到模式。

我的工具(为我自己创建)报告这些匹配项和组:

Match #0
[0]: public string Brand
["Type"] → [1]: string
["Name"] → [2]: Brand

Match #1
[0]: internal string YearModel
["Type"] → [1]: string
["Name"] → [2]: YearModel

Match #2
[0]: public List<User> HasRented
["Type"] → [1]: List<User>
["Name"] → [2]: HasRented

Match #3
[0]: public DateTime? SomeDateTime
["Type"] → [1]: DateTime?
["Name"] → [2]: SomeDateTime

Match #4
[0]: public int Amount;
["Type"] → [1]: int
["Name"] → [2]: Amount;

Match #5
[0]: public static string Name
["Type"] → [1]: string
["Name"] → [2]: Name

Match #6
[0]: public readonly string Address
["Type"] → [1]: string
["Name"] → [2]: Address

关于c# - 从磁盘上的 .cs 类文件获取属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43825289/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com