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

2019-02-11 13:24发布

I am using CodeDom to generate dynamic code based on user values. One of those values controls what the name of the class I'm generating is. I know I could sterilize the name based on language rules about valid class names using regular expressions, but I'd like to know if there is a specific method built into the framework to validate and/or sterilize a class name.

4条回答
何必那么认真
2楼-- · 2019-02-11 13:28

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.

查看更多
等我变得足够好
3楼-- · 2019-02-11 13:35

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!

查看更多
等我变得足够好
4楼-- · 2019-02-11 13:41
public static bool IsReservedKeyWord(string identifier)
        {
            Microsoft.CSharp.CSharpCodeProvider csharpProvider = new Microsoft.CSharp.CSharpCodeProvider();
            return csharpProvider.IsValidIdentifier(identifier);
        }
查看更多
再贱就再见
5楼-- · 2019-02-11 13:44

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)
查看更多
登录 后发表回答