Skip to main content
 首页 » 编程设计

c#之匹配属性类型的正则表达式 C#

2024年05月22日45kevingrace

我有一个程序,我必须检查是否有任何自动属性类型与类名匹配。

例如,如果我有:

public class User  
{ 
   //Some code here 
} 
 
 
public class Cars 
{ 
  public string Brand {get; set;} 
  public string YearModel {get; set;} 
  public List<User> HasRented {get; set;} 
} 

现在,我已经有了匹配类名的代码,所以我可以从“public class User”中获取名称“User”。问题是,我需要正则表达式从“List<User>”中获取“public List<User> HasRented {get; set;}”。当然,我想获得所有的属性类型。所以我也希望这两个“字符串”在正则表达式上匹配。

如果有任何帮助,我已经有了一个获取属性名称的正则表达式,所以也许有人可以帮我修改它以获取属性类型?

正则表达式:\w+(?=\s*{\s*get\b)

编辑: 忘记提及我将源作为字符串,这就是为什么我想将它与正则表达式匹配。要特别清楚:我唯一需要帮助的是正则表达式,用于从包含填充自动属性的类的文本中获取属性类型。不是与类名的匹配。

请您参考如下方法:

使用正则表达式解析代码是没有用的,因为属性的类型不限于 1 级泛型,可以是任何类似的东西

List<SortedList<string, User>> 

在这种情况下,最好让 C# 编译器 (csc) 来完成这项工作。

我假设代码当然可以编译,因为您的源代码缺少 System.Collections.Generic 所需的 using 语句;

编译源代码的代码如下:

    CSharpCodeProvider prov = new CSharpCodeProvider(); 
    CompilerResults results = prov.CompileAssemblyFromFile(new System.CodeDom.Compiler.CompilerParameters(), new string[] { "c:\\temp\\code.txt" }); 
    if (results.Errors.Count == 0) 
    { 
        Assembly assembly = results.CompiledAssembly; 
        foreach (Type type in assembly.GetTypes()) 
        { 
            Console.WriteLine("Type: {0}", type.Name); 
            foreach (PropertyInfo pi in type.GetProperties()) 
            { 
                Console.WriteLine("    Property: {0}, Return Type: {1}", pi.Name, pi.PropertyType); 
            } 
        } 
    } 

这是输出:

Type: User 
Type: Cars 
    Property: Brand, Return Type: System.String 
    Property: YearModel, Return Type: System.String 
    Property: HasRented, Return Type: System.Collections.Generic.List`1[User]