简体   繁体   English

列出 C# 关键字

[英]List C# keywords

I'm trying to find a way to list all C# keywords.我正在尝试找到一种列出所有 C# 关键字的方法。 I need to make a comparison, such as:我需要做一个比较,例如:

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

It would be way better to do it by searching in a list of those keywords, and I would like to do it without typing them.通过在这些关键字的列表中搜索来做到这一点会更好,我想在不输入它们的情况下进行。

I'm looking at System.CodeDom namespace to see if I can find something.我正在查看 System.CodeDom 命名空间,看看我是否能找到一些东西。

If any of you could tell me where I could find it, I would really appreciate it.如果有人能告诉我在哪里可以找到它,我将不胜感激。 Thank you in advance!提前谢谢你!

You can use你可以使用

using Microsoft.CSharp;

 CSharpCodeProvider cs = new CSharpCodeProvider();

then, you can use然后,你可以使用

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

You'll find a list of all keywords in the documentation: https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/index您将在文档中找到所有关键字的列表: 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 has the logic to do this. CSharpCodeProvider具有执行此操作的逻辑。 But you must call it with reflection.但是你必须用反射来调用它。 It contains an IsKeyword function.它包含一个IsKeyword函数。 More specifically, it has the actual list of keywords which IsKeyword uses.更具体地说,它具有IsKeyword使用的实际关键字列表。

private static readonly string[][] keywords

If you don't mind using reflection and a dependency on implementation details, you can use the static IsKeyWord method of the Microsoft.CSharp.CSharpCodeGenerator Class .如果您不介意使用反射和对实现细节的依赖,您可以使用Microsoft.CSharp.CSharpCodeGenerator Class的静态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() }));
        }
    }

Example usage:用法示例:

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

Thanks to Roslyn, you can do this with the Microsoft.CodeAnalysis.CSharp nuget package.感谢 Roslyn,您可以使用Microsoft.CodeAnalysis.CSharp nuget 包来做到这一点。

After adding this package, your code becomes:添加此包后,您的代码变为:

using Microsoft.CodeAnalysis.CSharp;
if (SyntaxFacts.GetKeywordKind(key) != SyntaxKind.None || SyntaxFacts.GetContextualKeywordKind(key) != SyntaxKind.None)
{
    // do something
}

If you need this to be as fast as possible, use a static field like:如果您需要尽可能快地执行此操作,请使用静态字段,例如:

private static readonly HashSet<string> Keywords =
    SyntaxFacts.GetKeywordKinds().Select(SyntaxFacts.GetText).ToHashSet();

Then, your code becomes:然后,您的代码变为:

if (Keywords.Contains(key))
{
    // do something
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM