如何从文件名生成安全类名?

Pau*_*ner 1 c# code-generation compilation razor

我正在尝试使用Razor引擎生成一些动态编译的代码,我想根据源文件名命名生成的类,以帮助理解生成的代码的来源.

例如,我希望文件C:\ source\Foo.cs可以使用名称进行编译Foo.

鉴于我有编译源文件的路径,有没有办法根据文件名生成有效的C#标识符?

DGi*_*bbs 8

根据C#规范,在创建标识符时必须遵守以下规则:

  • 标识符必须以字母或下划线开头
  • 在第一个字符之后,它可能包含数字,字母,连接符等
  • 如果标识符是关键字,则必须以"@"为前缀

这个助手将满足这些条件:

private static string GenerateClassName(string value)
{
    string className = CultureInfo.CurrentCulture.TextInfo.ToTitleCase(value);
    bool isValid = Microsoft.CSharp.CSharpCodeProvider.CreateProvider("C#").IsValidIdentifier(className);

    if (!isValid)
    { 
        // File name contains invalid chars, remove them
        Regex regex = new Regex(@"[^\p{Ll}\p{Lu}\p{Lt}\p{Lo}\p{Nd}\p{Nl}\p{Mn}\p{Mc}\p{Cf}\p{Pc}\p{Lm}]");
        className = regex.Replace(className, "");

        // Class name doesn't begin with a letter, insert an underscore
        if (!char.IsLetter(className, 0))
        {
            className = className.Insert(0, "_");
        }
    }

    return className.Replace(" ", string.Empty);
}
Run Code Online (Sandbox Code Playgroud)

它首先将文件名转换为驼峰大小写(个人偏好),然后使用IsValidIdentifier确定文件名是否已对类名有效.

如果没有,它将根据unicode字符类删除所有无效字符.然后它检查文件名是否以字母开头,如果是,它会预先_修复它.

最后,我删除所有空格(即使它仍然是一个有效的标识符).