gpt4 book ai didi

c# - 根据代码行从文本文件中获取函数名称

转载 作者:行者123 更新时间:2023-11-30 03:36:30 25 4
gpt4 key购买 nike

我有一个名为“MyCpp.cpp”的 C++ 源代码,它位于:C:\MyCpp.cpp

...
5 string CplusplusWarningFunction()
6 {
7 int a = 69;
8 int b = a + 1;
9 a = b;
10 b = 69;
11 return "42 is the answer";
12 }
...

现在我想写一个这样的C#函数

void CodeAnalyzer()
{
string path = @"C:\MyCpp.cpp";
int line = 11;
IEnumerable<string> loc = File.ReadLines(path);

string code = loc.ElementAt(line-1);//Yes, it is 'return "42 is the answer";', good job!
string functionFullName = "???";//This suppose to be the string 'CplusplusWarningFunction()', but How to do it???
MessageBox.Show(string.Format("The code {0} at line {1} is in function {2}",code,line,functionFullName));
}

如何获取函数名来替换字符串“???”在上面的 C# 代码中?

我知道这是可以做到的,因为 MS 的 FxCop 可以做到(FxCop 分析编译后的目标代码,而不是原始源代码)。好吧,如果编译后的目标代码可以完成,为什么不使用原始源代码。

而Visual Studio可以像下图那样做,我希望有一种方法可以访问Visual Studio API: enter image description here

感谢阅读。

最佳答案

鉴于只有一个功能,您可以尝试每一行

//do this in a foreach loop that will iterate through every line
string functionName;
if (line.Split(' ').Where(x => x.Contains("()") && !x.Contains(".")).Count() > 0)
{
functionName = line.Split(' ').Where(x => x.Contains("()") && !x.Contains(".")).First();
}

现在这将适用于您的示例代码,但这也是 非常 基本的,我敢肯定在很多情况下这都行不通。不过,这可能不是一个糟糕的起点。

关于c# - 根据代码行从文本文件中获取函数名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40657731/

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