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

C# 从磁盘上的.cs类文件获取属性,c#,.net,regex,vsix,C#,.net,Regex,Vsix,我正在为VisualStudio编写VSIX扩展。使用该插件,用户可以从VS中的解决方案资源管理器中选择一个类文件(即磁盘上某个位置的实际.cs文件),然后通过上下文菜单项触发我的VSIX代码,对该文件执行特定操作 我的VSIX扩展需要知道所选类文件的public和internal属性是什么 我试图通过使用正则表达式来解决这个问题,但我有点被它卡住了。我不知道如何只获取类的属性名。现在发现太多了 这是我到目前为止的正则表达式: \s*(?:(?:public|internal)\s+)?(?:s

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

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

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

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

\s*(?:(?:public|internal)\s+)?(?:static\s+)?(?:readonly\s+)?(\w+)\s+(\w+)\s*[^(]
演示: 在此演示中,我想提取所有属性名称,因此:

Brand,
YearModel,
HasRented,
SomeDateTime,
Amount,
Name,
Address
另外,我知道正则表达式并不适合这种工作。但是我想我没有任何其他的VSIX扩展选项

如何仅获取类的属性名称

此模式已注释,因此可以选择使用
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.

那么它的预期匹配是什么呢?这听起来像是对Microsoft编译器服务(Roslyn)的一个很好的使用。你为什么不认为你还有其他选择呢?我认为要获得一个可靠的、永远不会捕获误报的正则表达式是极其困难的。@Crowcoder据我所知,Roslyn编译器需要“有效”的代码。所以,当我给它任何一个类文件,其中包含使用语句的
,它也需要加载这些语句。它不能只编译大项目中的一个类文件。那么加载整个项目有什么问题呢?这正是内置的intellisense等,以及像ReSharper这样的东西所做的。而且,它可以解析任意代码块,如果存在不可用的引用,您可以从中获得的信息可能会有所不同。我不相信任何php表达式能在.Net中工作。
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