ToB企服应用市场:ToB评测及商务社交产业平台
标题:
C#判断代码片段为class还是method
[打印本页]
作者:
小小小幸运
时间:
2024-7-30 12:19
标题:
C#判断代码片段为class还是method
判断代码片段是class还是method:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
string codeSnippet1 = @"public class MyClass
{
bool b=false;
public void MyMethod()
{
int i=0;
// Method logic
}
}";
string codeSnippet2 = @"public void MyMethod()
{
// Method logic
}
public void MyMethod1()
{
// Method logic
}
";
Console.WriteLine(IsClassOrFunction(codeSnippet1)); // Output: Class
Console.WriteLine(IsClassOrFunction(codeSnippet2)); // Output: Function
}
static string IsClassOrFunction(string codeSnippet)
{
// Regular expression to match a class definition
var classRegex = new Regex(@"^\s*public\s+class\s+\w+", RegexOptions.Multiline);
// Regular expression to match a method definition
var methodRegex = new Regex(@"^\s*(public|private|protected|internal)?\s*(static\s+)?\w+\s+\w+\s*\(.*\)\s*\{", RegexOptions.Multiline);
if (classRegex.IsMatch(codeSnippet))
{
return "Class";
}
else if (methodRegex.IsMatch(codeSnippet))
{
return "Function";
}
else
{
return "Unknown";
}
}
}
复制代码
抽取class代码中的成员变量和成员方法:
using System;
using System.Linq;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
class Program
{
static void Main()
{
string codeSnippet = @"
public class MyClass
{
public int MyField;
private string _myPrivateField;
public void MyMethod()
{
// Method logic
}
private void MyPrivateMethod()
{
// Method logic
}
}";
AnalyzeClass(codeSnippet);
}
static void AnalyzeClass(string codeSnippet)
{
// Parse the code snippet
var tree = CSharpSyntaxTree.ParseText(codeSnippet);
var root = tree.GetRoot();
// Find the class declaration
var classDeclaration = root.DescendantNodes()
.OfType<ClassDeclarationSyntax>()
.FirstOrDefault();
if (classDeclaration != null)
{
Console.WriteLine($"Class: {classDeclaration.Identifier.Text}");
// Extract fields (member variables)
var fields = classDeclaration.Members
.OfType<FieldDeclarationSyntax>();
Console.WriteLine("Fields:");
foreach (var field in fields)
{
var fieldType = field.Declaration.Type.ToString();
foreach (var variable in field.Declaration.Variables)
{
Console.WriteLine($" {fieldType} {variable.Identifier.Text}");
}
}
// Extract methods
var methods = classDeclaration.Members
.OfType<MethodDeclarationSyntax>();
Console.WriteLine("Methods:");
foreach (var method in methods)
{
var returnType = method.ReturnType.ToString();
Console.WriteLine($" {returnType} {method.Identifier.Text}");
}
}
else
{
Console.WriteLine("No class declaration found.");
}
}
}
复制代码
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。
欢迎光临 ToB企服应用市场:ToB评测及商务社交产业平台 (https://dis.qidao123.com/)
Powered by Discuz! X3.4