列出C#关键字

我正试图找到一种列出所有C#关键字的方法。 我需要进行比较,例如:

if (key == "if" || key == "while" || ) { // do something } 

通过搜索这些关键字的列表来做这件事会更好,我想在不输入的情况下这样做。

我正在查看System.CodeDom命名空间,看看我是否能找到一些东西。

如果你们中的任何一个人能告诉我在哪里可以找到它,我会非常感激。 先感谢您!

您可以使用

using Microsoft.CSharp;

  CSharpCodeProvider cs = new CSharpCodeProvider(); 

那么,你可以使用

 var test = cs.IsValidIdentifier("if") //return false 

您可以在文档中找到所有关键字的列表: https : //docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/index

 new string[] { "bool", "byte", "sbyte", "short", "ushort", "int", "uint", "long", "ulong", "double", "float", "decimal", "string", "char", "void", "object", "typeof", "sizeof", "null", "true", "false", "if", "else", "while", "for", "foreach", "do", "switch", "case", "default", "lock", "try", "throw", "catch", "finally", "goto", "break", "continue", "return", "public", "private", "internal", "protected", "static", "readonly", "sealed", "const", "fixed", "stackalloc", "volatile", "new", "override", "abstract", "virtual", "event", "extern", "ref", "out", "in", "is", "as", "params", "__arglist", "__makeref", "__reftype", "__refvalue", "this", "base", "namespace", "using", "class", "struct", "interface", "enum", "delegate", "checked", "unchecked", "unsafe", "operator", "implicit", "explicit" }; 

CSharpCodeProvider具有执行此操作的逻辑。 但你必须用reflection来称呼它。 它包含一个IsKeyword函数。 更具体地说,它具有IsKeyword使用的实际关键字列表。

 private static readonly string[][] keywords 

如果您不介意使用reflection和依赖于实现细节,则可以使用Microsoft.CSharp.CSharpCodeGenerator类的静态IsKeyWord方法。

 using System; using System.CodeDom.Compiler; using Microsoft.CSharp; using System.Reflection; internal class CS { private static MethodInfo methIsKeyword; static CS() { using (CSharpCodeProvider cs = new CSharpCodeProvider()) { FieldInfo infoGenerator = cs.GetType().GetField("generator", BindingFlags.Instance | BindingFlags.NonPublic); object gen = infoGenerator.GetValue(cs); methIsKeyword = gen.GetType().GetMethod("IsKeyword", BindingFlags.Static | BindingFlags.NonPublic); } } public static bool IsKeyword(string input) { return Convert.ToBoolean(methIsKeyword.Invoke(null, new object[] { input.Trim() })); } } 

用法示例:

 bool isKeyword = CS.IsKeyword("if");