Regex C# - 如何匹配类的方法和属性名称 [英] Regex C# - how to match methods and properties names of a class
问题描述
我想匹配方法名称(带参数)和属性名称.我不想在匹配中包含访问器.例如我有这样的课程:
I want to match methods name (with parameters) and properties name. I dont want to include accessors in match. For example i got this kind of class:
public class test
{
public static string NA = "n/a";
public static DateTime DateParser(string dateToBeParsed)
{
DateTime returnValue = new DateTime();
DateTime.TryParse(dateToBeParsed, GetCulture(), System.Globalization.DateTimeStyles.AssumeLocal , out returnValue);
return returnValue;
}
}
对于类名,我正在使用这种正则表达式:(?<=class\s)[^\s]+ 对于我正在尝试这样的方法:[^\s]+(?=() 但这将选择所有具有 ( 的文本.对于方法,我需要选择具有 ( 和访问器,如 public、private 和 protected.如何在不将其包含在最终匹配中的情况下执行此操作?我只需要括号内的方法名称和参数.
For class name I'm using this kind of regex: (?<=class\s)[^\s]+ for methods im trying something like this: [^\s]+(?=() but this will select all that text that has (. For methods i need to select that line that has ( and accessors like public,private and protected. How to do it without including this in final match ? I need only method name and parameters within parenthesis.
推荐答案
如何使用反射?
class Program
{
static void Main(string[] args)
{
string assemblyName = Path.Combine(Path.GetTempPath(), string.Format("temp{0}.dll", Guid.NewGuid()));
CSharpCodeProvider codeProvider = new CSharpCodeProvider();
CompilerParameters compilerParameters = new CompilerParameters(new string[]
{
"System.dll",
"Microsoft.CSharp.dll",
}, assemblyName);
CompilerResults cr = codeProvider.CompileAssemblyFromSource(compilerParameters, File.ReadAllText("Program.cs"));
if (cr.Errors.Count > 0)
{
foreach (CompilerError error in cr.Errors)
{
Console.WriteLine(error.ErrorText);
}
}
else
{
AppDomain appDomain = AppDomain.CreateDomain("volatile");
Proxy p = (Proxy)appDomain.CreateInstanceAndUnwrap(Assembly.GetExecutingAssembly().FullName, typeof(Proxy).FullName);
p.ShowTypesStructure(assemblyName);
AppDomain.Unload(appDomain);
File.Delete(assemblyName);
}
Console.ReadLine();
}
}
public class Proxy : MarshalByRefObject
{
public void ShowTypesStructure(string assemblyName)
{
Assembly assembly = Assembly.LoadFrom(assemblyName);
Type[] types = assembly.GetTypes();
foreach (Type type in types)
{
Console.WriteLine(type.Name);
MethodInfo[] mis = type.GetMethods();
foreach (MethodInfo mi in mis)
{
Console.WriteLine("\t" + mi.Name);
}
}
}
}
这篇关于Regex C# - 如何匹配类的方法和属性名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!