Is there a .NET function to validate a class name?

佐手、 提交于 2019-11-30 17:06:41

An easy way to determine if a string is a valid identifier for a class or variable is to call the static method

System.CodeDom.Compiler.CodeGenerator.IsValidLanguageIndependentIdentifier(string value)
Jason Diller

Use the CreateValidIdentifier method on the CSharpCodeProvider class.

CSharpCodeProvider codeProvider = new CSharpCodeProvider(); 
string sFixedName = codeProvider.CreateValidIdentifier("somePossiblyInvalidName"); 
CodeTypeDeclaration codeType = new CodeTypeDeclaration(sFixedName); 

It returns a valid name given some input. If you just want to validate the name and not fix it, compare the input and output. It won't alter valid input so the output will be equivalent.

I found an answer to my question. I can call

CodeCompiler.ValidateIdentifiers(class1);

where class1 is a CodeObject to validate all identifiers in that CodeDom tree and below. So I can call this right after I create my CodeTypeDeclaration class1 to validate just the class name, or I can build up my CodeDom and then call this at the end to validate all the identifiers in my tree. Just what I needed!

public static bool IsReservedKeyWord(string identifier)
        {
            Microsoft.CSharp.CSharpCodeProvider csharpProvider = new Microsoft.CSharp.CSharpCodeProvider();
            return csharpProvider.IsValidIdentifier(identifier);
        }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!