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

标签 c# .net regex vsix

我正在为 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/

相关文章:

c# - 如何使用 Titanium-Web-Proxy 编写反向代理?

c# - 为什么 GetHashCode() 很重要?

regex - 正则表达式 - 接受 15 到 17 位数字

c# - C# WPF 中的 "Simple MVVM Toolkit"子模型类

c# - 如何取消对匿名方法回调的监听?

c# - 从 UserPrincipal 对象获取 nETBIOSName

.net - CAML 查询比较 DateTime 与 Eq

c# - 将 .net 4.5 应用程序降级到 4.0

python搜索/用类似sed的表达式替换正则表达式

javascript - 时间比较验证器